PackageManagerService.java revision 1d0e83d2cee794ba576d573119e826905a4422cd
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        boolean updatedPkgBetter = false;
8923        // First check if this is a system package that may involve an update
8924        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8925            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8926            // it needs to drop FLAG_PRIVILEGED.
8927            if (locationIsPrivileged(scanFile)) {
8928                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8929            } else {
8930                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8931            }
8932
8933            if (ps != null && !ps.codePath.equals(scanFile)) {
8934                // The path has changed from what was last scanned...  check the
8935                // version of the new path against what we have stored to determine
8936                // what to do.
8937                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8938                if (pkg.mVersionCode <= ps.versionCode) {
8939                    // The system package has been updated and the code path does not match
8940                    // Ignore entry. Skip it.
8941                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8942                            + " ignored: updated version " + ps.versionCode
8943                            + " better than this " + pkg.mVersionCode);
8944                    if (!updatedPkg.codePath.equals(scanFile)) {
8945                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8946                                + ps.name + " changing from " + updatedPkg.codePathString
8947                                + " to " + scanFile);
8948                        updatedPkg.codePath = scanFile;
8949                        updatedPkg.codePathString = scanFile.toString();
8950                        updatedPkg.resourcePath = scanFile;
8951                        updatedPkg.resourcePathString = scanFile.toString();
8952                    }
8953                    updatedPkg.pkg = pkg;
8954                    updatedPkg.versionCode = pkg.mVersionCode;
8955
8956                    // Update the disabled system child packages to point to the package too.
8957                    final int childCount = updatedPkg.childPackageNames != null
8958                            ? updatedPkg.childPackageNames.size() : 0;
8959                    for (int i = 0; i < childCount; i++) {
8960                        String childPackageName = updatedPkg.childPackageNames.get(i);
8961                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8962                                childPackageName);
8963                        if (updatedChildPkg != null) {
8964                            updatedChildPkg.pkg = pkg;
8965                            updatedChildPkg.versionCode = pkg.mVersionCode;
8966                        }
8967                    }
8968
8969                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8970                            + scanFile + " ignored: updated version " + ps.versionCode
8971                            + " better than this " + pkg.mVersionCode);
8972                } else {
8973                    // The current app on the system partition is better than
8974                    // what we have updated to on the data partition; switch
8975                    // back to the system partition version.
8976                    // At this point, its safely assumed that package installation for
8977                    // apps in system partition will go through. If not there won't be a working
8978                    // version of the app
8979                    // writer
8980                    synchronized (mPackages) {
8981                        // Just remove the loaded entries from package lists.
8982                        mPackages.remove(ps.name);
8983                    }
8984
8985                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8986                            + " reverting from " + ps.codePathString
8987                            + ": new version " + pkg.mVersionCode
8988                            + " better than installed " + ps.versionCode);
8989
8990                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8991                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8992                    synchronized (mInstallLock) {
8993                        args.cleanUpResourcesLI();
8994                    }
8995                    synchronized (mPackages) {
8996                        mSettings.enableSystemPackageLPw(ps.name);
8997                    }
8998                    updatedPkgBetter = true;
8999                }
9000            }
9001        }
9002
9003        if (updatedPkg != null) {
9004            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9005            // initially
9006            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9007
9008            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9009            // flag set initially
9010            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9011                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9012            }
9013        }
9014
9015        // Verify certificates against what was last scanned
9016        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9017
9018        /*
9019         * A new system app appeared, but we already had a non-system one of the
9020         * same name installed earlier.
9021         */
9022        boolean shouldHideSystemApp = false;
9023        if (updatedPkg == null && ps != null
9024                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9025            /*
9026             * Check to make sure the signatures match first. If they don't,
9027             * wipe the installed application and its data.
9028             */
9029            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9030                    != PackageManager.SIGNATURE_MATCH) {
9031                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9032                        + " signatures don't match existing userdata copy; removing");
9033                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9034                        "scanPackageInternalLI")) {
9035                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9036                }
9037                ps = null;
9038            } else {
9039                /*
9040                 * If the newly-added system app is an older version than the
9041                 * already installed version, hide it. It will be scanned later
9042                 * and re-added like an update.
9043                 */
9044                if (pkg.mVersionCode <= ps.versionCode) {
9045                    shouldHideSystemApp = true;
9046                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9047                            + " but new version " + pkg.mVersionCode + " better than installed "
9048                            + ps.versionCode + "; hiding system");
9049                } else {
9050                    /*
9051                     * The newly found system app is a newer version that the
9052                     * one previously installed. Simply remove the
9053                     * already-installed application and replace it with our own
9054                     * while keeping the application data.
9055                     */
9056                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9057                            + " reverting from " + ps.codePathString + ": new version "
9058                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9059                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9060                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9061                    synchronized (mInstallLock) {
9062                        args.cleanUpResourcesLI();
9063                    }
9064                }
9065            }
9066        }
9067
9068        // The apk is forward locked (not public) if its code and resources
9069        // are kept in different files. (except for app in either system or
9070        // vendor path).
9071        // TODO grab this value from PackageSettings
9072        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9073            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9074                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9075            }
9076        }
9077
9078        // TODO: extend to support forward-locked splits
9079        String resourcePath = null;
9080        String baseResourcePath = null;
9081        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
9082            if (ps != null && ps.resourcePathString != null) {
9083                resourcePath = ps.resourcePathString;
9084                baseResourcePath = ps.resourcePathString;
9085            } else {
9086                // Should not happen at all. Just log an error.
9087                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9088            }
9089        } else {
9090            resourcePath = pkg.codePath;
9091            baseResourcePath = pkg.baseCodePath;
9092        }
9093
9094        // Set application objects path explicitly.
9095        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9096        pkg.setApplicationInfoCodePath(pkg.codePath);
9097        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9098        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9099        pkg.setApplicationInfoResourcePath(resourcePath);
9100        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9101        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9102
9103        final int userId = ((user == null) ? 0 : user.getIdentifier());
9104        if (ps != null && ps.getInstantApp(userId)) {
9105            scanFlags |= SCAN_AS_INSTANT_APP;
9106        }
9107
9108        // Note that we invoke the following method only if we are about to unpack an application
9109        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9110                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9111
9112        /*
9113         * If the system app should be overridden by a previously installed
9114         * data, hide the system app now and let the /data/app scan pick it up
9115         * again.
9116         */
9117        if (shouldHideSystemApp) {
9118            synchronized (mPackages) {
9119                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9120            }
9121        }
9122
9123        return scannedPkg;
9124    }
9125
9126    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9127        // Derive the new package synthetic package name
9128        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9129                + pkg.staticSharedLibVersion);
9130    }
9131
9132    private static String fixProcessName(String defProcessName,
9133            String processName) {
9134        if (processName == null) {
9135            return defProcessName;
9136        }
9137        return processName;
9138    }
9139
9140    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9141            throws PackageManagerException {
9142        if (pkgSetting.signatures.mSignatures != null) {
9143            // Already existing package. Make sure signatures match
9144            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9145                    == PackageManager.SIGNATURE_MATCH;
9146            if (!match) {
9147                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9148                        == PackageManager.SIGNATURE_MATCH;
9149            }
9150            if (!match) {
9151                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9152                        == PackageManager.SIGNATURE_MATCH;
9153            }
9154            if (!match) {
9155                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9156                        + pkg.packageName + " signatures do not match the "
9157                        + "previously installed version; ignoring!");
9158            }
9159        }
9160
9161        // Check for shared user signatures
9162        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9163            // Already existing package. Make sure signatures match
9164            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9165                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9166            if (!match) {
9167                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9168                        == PackageManager.SIGNATURE_MATCH;
9169            }
9170            if (!match) {
9171                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9172                        == PackageManager.SIGNATURE_MATCH;
9173            }
9174            if (!match) {
9175                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9176                        "Package " + pkg.packageName
9177                        + " has no signatures that match those in shared user "
9178                        + pkgSetting.sharedUser.name + "; ignoring!");
9179            }
9180        }
9181    }
9182
9183    /**
9184     * Enforces that only the system UID or root's UID can call a method exposed
9185     * via Binder.
9186     *
9187     * @param message used as message if SecurityException is thrown
9188     * @throws SecurityException if the caller is not system or root
9189     */
9190    private static final void enforceSystemOrRoot(String message) {
9191        final int uid = Binder.getCallingUid();
9192        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9193            throw new SecurityException(message);
9194        }
9195    }
9196
9197    @Override
9198    public void performFstrimIfNeeded() {
9199        enforceSystemOrRoot("Only the system can request fstrim");
9200
9201        // Before everything else, see whether we need to fstrim.
9202        try {
9203            IStorageManager sm = PackageHelper.getStorageManager();
9204            if (sm != null) {
9205                boolean doTrim = false;
9206                final long interval = android.provider.Settings.Global.getLong(
9207                        mContext.getContentResolver(),
9208                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9209                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9210                if (interval > 0) {
9211                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9212                    if (timeSinceLast > interval) {
9213                        doTrim = true;
9214                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9215                                + "; running immediately");
9216                    }
9217                }
9218                if (doTrim) {
9219                    final boolean dexOptDialogShown;
9220                    synchronized (mPackages) {
9221                        dexOptDialogShown = mDexOptDialogShown;
9222                    }
9223                    if (!isFirstBoot() && dexOptDialogShown) {
9224                        try {
9225                            ActivityManager.getService().showBootMessage(
9226                                    mContext.getResources().getString(
9227                                            R.string.android_upgrading_fstrim), true);
9228                        } catch (RemoteException e) {
9229                        }
9230                    }
9231                    sm.runMaintenance();
9232                }
9233            } else {
9234                Slog.e(TAG, "storageManager service unavailable!");
9235            }
9236        } catch (RemoteException e) {
9237            // Can't happen; StorageManagerService is local
9238        }
9239    }
9240
9241    @Override
9242    public void updatePackagesIfNeeded() {
9243        enforceSystemOrRoot("Only the system can request package update");
9244
9245        // We need to re-extract after an OTA.
9246        boolean causeUpgrade = isUpgrade();
9247
9248        // First boot or factory reset.
9249        // Note: we also handle devices that are upgrading to N right now as if it is their
9250        //       first boot, as they do not have profile data.
9251        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9252
9253        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9254        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9255
9256        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9257            return;
9258        }
9259
9260        List<PackageParser.Package> pkgs;
9261        synchronized (mPackages) {
9262            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9263        }
9264
9265        final long startTime = System.nanoTime();
9266        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9267                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9268                    false /* bootComplete */);
9269
9270        final int elapsedTimeSeconds =
9271                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9272
9273        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9274        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9275        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9276        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9277        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9278    }
9279
9280    /*
9281     * Return the prebuilt profile path given a package base code path.
9282     */
9283    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9284        return pkg.baseCodePath + ".prof";
9285    }
9286
9287    /**
9288     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9289     * containing statistics about the invocation. The array consists of three elements,
9290     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9291     * and {@code numberOfPackagesFailed}.
9292     */
9293    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9294            String compilerFilter, boolean bootComplete) {
9295
9296        int numberOfPackagesVisited = 0;
9297        int numberOfPackagesOptimized = 0;
9298        int numberOfPackagesSkipped = 0;
9299        int numberOfPackagesFailed = 0;
9300        final int numberOfPackagesToDexopt = pkgs.size();
9301
9302        for (PackageParser.Package pkg : pkgs) {
9303            numberOfPackagesVisited++;
9304
9305            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9306                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9307                // that are already compiled.
9308                File profileFile = new File(getPrebuildProfilePath(pkg));
9309                // Copy profile if it exists.
9310                if (profileFile.exists()) {
9311                    try {
9312                        // We could also do this lazily before calling dexopt in
9313                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9314                        // is that we don't have a good way to say "do this only once".
9315                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9316                                pkg.applicationInfo.uid, pkg.packageName)) {
9317                            Log.e(TAG, "Installer failed to copy system profile!");
9318                        }
9319                    } catch (Exception e) {
9320                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9321                                e);
9322                    }
9323                }
9324            }
9325
9326            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9327                if (DEBUG_DEXOPT) {
9328                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9329                }
9330                numberOfPackagesSkipped++;
9331                continue;
9332            }
9333
9334            if (DEBUG_DEXOPT) {
9335                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9336                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9337            }
9338
9339            if (showDialog) {
9340                try {
9341                    ActivityManager.getService().showBootMessage(
9342                            mContext.getResources().getString(R.string.android_upgrading_apk,
9343                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9344                } catch (RemoteException e) {
9345                }
9346                synchronized (mPackages) {
9347                    mDexOptDialogShown = true;
9348                }
9349            }
9350
9351            // If the OTA updates a system app which was previously preopted to a non-preopted state
9352            // the app might end up being verified at runtime. That's because by default the apps
9353            // are verify-profile but for preopted apps there's no profile.
9354            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9355            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9356            // filter (by default 'quicken').
9357            // Note that at this stage unused apps are already filtered.
9358            if (isSystemApp(pkg) &&
9359                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9360                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9361                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9362            }
9363
9364            // checkProfiles is false to avoid merging profiles during boot which
9365            // might interfere with background compilation (b/28612421).
9366            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9367            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9368            // trade-off worth doing to save boot time work.
9369            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9370            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9371                    pkg.packageName,
9372                    compilerFilter,
9373                    dexoptFlags));
9374
9375            if (pkg.isSystemApp()) {
9376                // Only dexopt shared secondary dex files belonging to system apps to not slow down
9377                // too much boot after an OTA.
9378                int secondaryDexoptFlags = dexoptFlags |
9379                        DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9380                        DexoptOptions.DEXOPT_ONLY_SHARED_DEX;
9381                mDexManager.dexoptSecondaryDex(new DexoptOptions(
9382                        pkg.packageName,
9383                        compilerFilter,
9384                        secondaryDexoptFlags));
9385            }
9386
9387            // TODO(shubhamajmera): Record secondary dexopt stats.
9388            switch (primaryDexOptStaus) {
9389                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9390                    numberOfPackagesOptimized++;
9391                    break;
9392                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9393                    numberOfPackagesSkipped++;
9394                    break;
9395                case PackageDexOptimizer.DEX_OPT_FAILED:
9396                    numberOfPackagesFailed++;
9397                    break;
9398                default:
9399                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9400                    break;
9401            }
9402        }
9403
9404        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9405                numberOfPackagesFailed };
9406    }
9407
9408    @Override
9409    public void notifyPackageUse(String packageName, int reason) {
9410        synchronized (mPackages) {
9411            final int callingUid = Binder.getCallingUid();
9412            final int callingUserId = UserHandle.getUserId(callingUid);
9413            if (getInstantAppPackageName(callingUid) != null) {
9414                if (!isCallerSameApp(packageName, callingUid)) {
9415                    return;
9416                }
9417            } else {
9418                if (isInstantApp(packageName, callingUserId)) {
9419                    return;
9420                }
9421            }
9422            final PackageParser.Package p = mPackages.get(packageName);
9423            if (p == null) {
9424                return;
9425            }
9426            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9427        }
9428    }
9429
9430    @Override
9431    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
9432        int userId = UserHandle.getCallingUserId();
9433        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9434        if (ai == null) {
9435            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9436                + loadingPackageName + ", user=" + userId);
9437            return;
9438        }
9439        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
9440    }
9441
9442    @Override
9443    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9444            IDexModuleRegisterCallback callback) {
9445        int userId = UserHandle.getCallingUserId();
9446        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9447        DexManager.RegisterDexModuleResult result;
9448        if (ai == null) {
9449            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9450                     " calling user. package=" + packageName + ", user=" + userId);
9451            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9452        } else {
9453            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9454        }
9455
9456        if (callback != null) {
9457            mHandler.post(() -> {
9458                try {
9459                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9460                } catch (RemoteException e) {
9461                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9462                }
9463            });
9464        }
9465    }
9466
9467    /**
9468     * Ask the package manager to perform a dex-opt with the given compiler filter.
9469     *
9470     * Note: exposed only for the shell command to allow moving packages explicitly to a
9471     *       definite state.
9472     */
9473    @Override
9474    public boolean performDexOptMode(String packageName,
9475            boolean checkProfiles, String targetCompilerFilter, boolean force,
9476            boolean bootComplete) {
9477        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9478                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9479                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9480        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter, flags));
9481    }
9482
9483    /**
9484     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9485     * secondary dex files belonging to the given package.
9486     *
9487     * Note: exposed only for the shell command to allow moving packages explicitly to a
9488     *       definite state.
9489     */
9490    @Override
9491    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9492            boolean force) {
9493        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9494                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9495                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9496                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9497        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9498    }
9499
9500    /*package*/ boolean performDexOpt(DexoptOptions options) {
9501        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9502            return false;
9503        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9504            return false;
9505        }
9506
9507        if (options.isDexoptOnlySecondaryDex()) {
9508            return mDexManager.dexoptSecondaryDex(options);
9509        } else {
9510            int dexoptStatus = performDexOptWithStatus(options);
9511            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9512        }
9513    }
9514
9515    /**
9516     * Perform dexopt on the given package and return one of following result:
9517     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9518     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9519     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9520     */
9521    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9522        return performDexOptTraced(options);
9523    }
9524
9525    private int performDexOptTraced(DexoptOptions options) {
9526        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9527        try {
9528            return performDexOptInternal(options);
9529        } finally {
9530            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9531        }
9532    }
9533
9534    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9535    // if the package can now be considered up to date for the given filter.
9536    private int performDexOptInternal(DexoptOptions options) {
9537        PackageParser.Package p;
9538        synchronized (mPackages) {
9539            p = mPackages.get(options.getPackageName());
9540            if (p == null) {
9541                // Package could not be found. Report failure.
9542                return PackageDexOptimizer.DEX_OPT_FAILED;
9543            }
9544            mPackageUsage.maybeWriteAsync(mPackages);
9545            mCompilerStats.maybeWriteAsync();
9546        }
9547        long callingId = Binder.clearCallingIdentity();
9548        try {
9549            synchronized (mInstallLock) {
9550                return performDexOptInternalWithDependenciesLI(p, options);
9551            }
9552        } finally {
9553            Binder.restoreCallingIdentity(callingId);
9554        }
9555    }
9556
9557    public ArraySet<String> getOptimizablePackages() {
9558        ArraySet<String> pkgs = new ArraySet<String>();
9559        synchronized (mPackages) {
9560            for (PackageParser.Package p : mPackages.values()) {
9561                if (PackageDexOptimizer.canOptimizePackage(p)) {
9562                    pkgs.add(p.packageName);
9563                }
9564            }
9565        }
9566        return pkgs;
9567    }
9568
9569    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9570            DexoptOptions options) {
9571        // Select the dex optimizer based on the force parameter.
9572        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9573        //       allocate an object here.
9574        PackageDexOptimizer pdo = options.isForce()
9575                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9576                : mPackageDexOptimizer;
9577
9578        // Dexopt all dependencies first. Note: we ignore the return value and march on
9579        // on errors.
9580        // Note that we are going to call performDexOpt on those libraries as many times as
9581        // they are referenced in packages. When we do a batch of performDexOpt (for example
9582        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9583        // and the first package that uses the library will dexopt it. The
9584        // others will see that the compiled code for the library is up to date.
9585        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9586        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9587        if (!deps.isEmpty()) {
9588            for (PackageParser.Package depPackage : deps) {
9589                // TODO: Analyze and investigate if we (should) profile libraries.
9590                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9591                        getOrCreateCompilerPackageStats(depPackage),
9592                        true /* isUsedByOtherApps */,
9593                        options);
9594            }
9595        }
9596        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9597                getOrCreateCompilerPackageStats(p),
9598                mDexManager.isUsedByOtherApps(p.packageName), options);
9599    }
9600
9601    /**
9602     * Reconcile the information we have about the secondary dex files belonging to
9603     * {@code packagName} and the actual dex files. For all dex files that were
9604     * deleted, update the internal records and delete the generated oat files.
9605     */
9606    @Override
9607    public void reconcileSecondaryDexFiles(String packageName) {
9608        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9609            return;
9610        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9611            return;
9612        }
9613        mDexManager.reconcileSecondaryDexFiles(packageName);
9614    }
9615
9616    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9617    // a reference there.
9618    /*package*/ DexManager getDexManager() {
9619        return mDexManager;
9620    }
9621
9622    /**
9623     * Execute the background dexopt job immediately.
9624     */
9625    @Override
9626    public boolean runBackgroundDexoptJob() {
9627        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9628            return false;
9629        }
9630        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9631    }
9632
9633    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9634        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9635                || p.usesStaticLibraries != null) {
9636            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9637            Set<String> collectedNames = new HashSet<>();
9638            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9639
9640            retValue.remove(p);
9641
9642            return retValue;
9643        } else {
9644            return Collections.emptyList();
9645        }
9646    }
9647
9648    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9649            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9650        if (!collectedNames.contains(p.packageName)) {
9651            collectedNames.add(p.packageName);
9652            collected.add(p);
9653
9654            if (p.usesLibraries != null) {
9655                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9656                        null, collected, collectedNames);
9657            }
9658            if (p.usesOptionalLibraries != null) {
9659                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9660                        null, collected, collectedNames);
9661            }
9662            if (p.usesStaticLibraries != null) {
9663                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9664                        p.usesStaticLibrariesVersions, collected, collectedNames);
9665            }
9666        }
9667    }
9668
9669    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9670            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9671        final int libNameCount = libs.size();
9672        for (int i = 0; i < libNameCount; i++) {
9673            String libName = libs.get(i);
9674            int version = (versions != null && versions.length == libNameCount)
9675                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9676            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9677            if (libPkg != null) {
9678                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9679            }
9680        }
9681    }
9682
9683    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9684        synchronized (mPackages) {
9685            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9686            if (libEntry != null) {
9687                return mPackages.get(libEntry.apk);
9688            }
9689            return null;
9690        }
9691    }
9692
9693    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9694        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9695        if (versionedLib == null) {
9696            return null;
9697        }
9698        return versionedLib.get(version);
9699    }
9700
9701    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9702        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9703                pkg.staticSharedLibName);
9704        if (versionedLib == null) {
9705            return null;
9706        }
9707        int previousLibVersion = -1;
9708        final int versionCount = versionedLib.size();
9709        for (int i = 0; i < versionCount; i++) {
9710            final int libVersion = versionedLib.keyAt(i);
9711            if (libVersion < pkg.staticSharedLibVersion) {
9712                previousLibVersion = Math.max(previousLibVersion, libVersion);
9713            }
9714        }
9715        if (previousLibVersion >= 0) {
9716            return versionedLib.get(previousLibVersion);
9717        }
9718        return null;
9719    }
9720
9721    public void shutdown() {
9722        mPackageUsage.writeNow(mPackages);
9723        mCompilerStats.writeNow();
9724    }
9725
9726    @Override
9727    public void dumpProfiles(String packageName) {
9728        PackageParser.Package pkg;
9729        synchronized (mPackages) {
9730            pkg = mPackages.get(packageName);
9731            if (pkg == null) {
9732                throw new IllegalArgumentException("Unknown package: " + packageName);
9733            }
9734        }
9735        /* Only the shell, root, or the app user should be able to dump profiles. */
9736        int callingUid = Binder.getCallingUid();
9737        if (callingUid != Process.SHELL_UID &&
9738            callingUid != Process.ROOT_UID &&
9739            callingUid != pkg.applicationInfo.uid) {
9740            throw new SecurityException("dumpProfiles");
9741        }
9742
9743        synchronized (mInstallLock) {
9744            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9745            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9746            try {
9747                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9748                String codePaths = TextUtils.join(";", allCodePaths);
9749                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9750            } catch (InstallerException e) {
9751                Slog.w(TAG, "Failed to dump profiles", e);
9752            }
9753            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9754        }
9755    }
9756
9757    @Override
9758    public void forceDexOpt(String packageName) {
9759        enforceSystemOrRoot("forceDexOpt");
9760
9761        PackageParser.Package pkg;
9762        synchronized (mPackages) {
9763            pkg = mPackages.get(packageName);
9764            if (pkg == null) {
9765                throw new IllegalArgumentException("Unknown package: " + packageName);
9766            }
9767        }
9768
9769        synchronized (mInstallLock) {
9770            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9771
9772            // Whoever is calling forceDexOpt wants a compiled package.
9773            // Don't use profiles since that may cause compilation to be skipped.
9774            final int res = performDexOptInternalWithDependenciesLI(
9775                    pkg,
9776                    new DexoptOptions(packageName,
9777                            getDefaultCompilerFilter(),
9778                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9779
9780            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9781            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9782                throw new IllegalStateException("Failed to dexopt: " + res);
9783            }
9784        }
9785    }
9786
9787    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9788        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9789            Slog.w(TAG, "Unable to update from " + oldPkg.name
9790                    + " to " + newPkg.packageName
9791                    + ": old package not in system partition");
9792            return false;
9793        } else if (mPackages.get(oldPkg.name) != null) {
9794            Slog.w(TAG, "Unable to update from " + oldPkg.name
9795                    + " to " + newPkg.packageName
9796                    + ": old package still exists");
9797            return false;
9798        }
9799        return true;
9800    }
9801
9802    void removeCodePathLI(File codePath) {
9803        if (codePath.isDirectory()) {
9804            try {
9805                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9806            } catch (InstallerException e) {
9807                Slog.w(TAG, "Failed to remove code path", e);
9808            }
9809        } else {
9810            codePath.delete();
9811        }
9812    }
9813
9814    private int[] resolveUserIds(int userId) {
9815        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9816    }
9817
9818    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9819        if (pkg == null) {
9820            Slog.wtf(TAG, "Package was null!", new Throwable());
9821            return;
9822        }
9823        clearAppDataLeafLIF(pkg, userId, flags);
9824        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9825        for (int i = 0; i < childCount; i++) {
9826            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9827        }
9828    }
9829
9830    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9831        final PackageSetting ps;
9832        synchronized (mPackages) {
9833            ps = mSettings.mPackages.get(pkg.packageName);
9834        }
9835        for (int realUserId : resolveUserIds(userId)) {
9836            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9837            try {
9838                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9839                        ceDataInode);
9840            } catch (InstallerException e) {
9841                Slog.w(TAG, String.valueOf(e));
9842            }
9843        }
9844    }
9845
9846    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9847        if (pkg == null) {
9848            Slog.wtf(TAG, "Package was null!", new Throwable());
9849            return;
9850        }
9851        destroyAppDataLeafLIF(pkg, userId, flags);
9852        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9853        for (int i = 0; i < childCount; i++) {
9854            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9855        }
9856    }
9857
9858    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9859        final PackageSetting ps;
9860        synchronized (mPackages) {
9861            ps = mSettings.mPackages.get(pkg.packageName);
9862        }
9863        for (int realUserId : resolveUserIds(userId)) {
9864            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9865            try {
9866                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9867                        ceDataInode);
9868            } catch (InstallerException e) {
9869                Slog.w(TAG, String.valueOf(e));
9870            }
9871            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9872        }
9873    }
9874
9875    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9876        if (pkg == null) {
9877            Slog.wtf(TAG, "Package was null!", new Throwable());
9878            return;
9879        }
9880        destroyAppProfilesLeafLIF(pkg);
9881        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9882        for (int i = 0; i < childCount; i++) {
9883            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9884        }
9885    }
9886
9887    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9888        try {
9889            mInstaller.destroyAppProfiles(pkg.packageName);
9890        } catch (InstallerException e) {
9891            Slog.w(TAG, String.valueOf(e));
9892        }
9893    }
9894
9895    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9896        if (pkg == null) {
9897            Slog.wtf(TAG, "Package was null!", new Throwable());
9898            return;
9899        }
9900        clearAppProfilesLeafLIF(pkg);
9901        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9902        for (int i = 0; i < childCount; i++) {
9903            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9904        }
9905    }
9906
9907    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9908        try {
9909            mInstaller.clearAppProfiles(pkg.packageName);
9910        } catch (InstallerException e) {
9911            Slog.w(TAG, String.valueOf(e));
9912        }
9913    }
9914
9915    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9916            long lastUpdateTime) {
9917        // Set parent install/update time
9918        PackageSetting ps = (PackageSetting) pkg.mExtras;
9919        if (ps != null) {
9920            ps.firstInstallTime = firstInstallTime;
9921            ps.lastUpdateTime = lastUpdateTime;
9922        }
9923        // Set children install/update time
9924        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9925        for (int i = 0; i < childCount; i++) {
9926            PackageParser.Package childPkg = pkg.childPackages.get(i);
9927            ps = (PackageSetting) childPkg.mExtras;
9928            if (ps != null) {
9929                ps.firstInstallTime = firstInstallTime;
9930                ps.lastUpdateTime = lastUpdateTime;
9931            }
9932        }
9933    }
9934
9935    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
9936            PackageParser.Package changingLib) {
9937        if (file.path != null) {
9938            usesLibraryFiles.add(file.path);
9939            return;
9940        }
9941        PackageParser.Package p = mPackages.get(file.apk);
9942        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9943            // If we are doing this while in the middle of updating a library apk,
9944            // then we need to make sure to use that new apk for determining the
9945            // dependencies here.  (We haven't yet finished committing the new apk
9946            // to the package manager state.)
9947            if (p == null || p.packageName.equals(changingLib.packageName)) {
9948                p = changingLib;
9949            }
9950        }
9951        if (p != null) {
9952            usesLibraryFiles.addAll(p.getAllCodePaths());
9953            if (p.usesLibraryFiles != null) {
9954                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9955            }
9956        }
9957    }
9958
9959    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9960            PackageParser.Package changingLib) throws PackageManagerException {
9961        if (pkg == null) {
9962            return;
9963        }
9964        ArraySet<String> usesLibraryFiles = null;
9965        if (pkg.usesLibraries != null) {
9966            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9967                    null, null, pkg.packageName, changingLib, true, null);
9968        }
9969        if (pkg.usesStaticLibraries != null) {
9970            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9971                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9972                    pkg.packageName, changingLib, true, usesLibraryFiles);
9973        }
9974        if (pkg.usesOptionalLibraries != null) {
9975            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9976                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
9977        }
9978        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9979            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9980        } else {
9981            pkg.usesLibraryFiles = null;
9982        }
9983    }
9984
9985    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9986            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
9987            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9988            boolean required, @Nullable ArraySet<String> outUsedLibraries)
9989            throws PackageManagerException {
9990        final int libCount = requestedLibraries.size();
9991        for (int i = 0; i < libCount; i++) {
9992            final String libName = requestedLibraries.get(i);
9993            final int libVersion = requiredVersions != null ? requiredVersions[i]
9994                    : SharedLibraryInfo.VERSION_UNDEFINED;
9995            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9996            if (libEntry == null) {
9997                if (required) {
9998                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9999                            "Package " + packageName + " requires unavailable shared library "
10000                                    + libName + "; failing!");
10001                } else if (DEBUG_SHARED_LIBRARIES) {
10002                    Slog.i(TAG, "Package " + packageName
10003                            + " desires unavailable shared library "
10004                            + libName + "; ignoring!");
10005                }
10006            } else {
10007                if (requiredVersions != null && requiredCertDigests != null) {
10008                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10009                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10010                            "Package " + packageName + " requires unavailable static shared"
10011                                    + " library " + libName + " version "
10012                                    + libEntry.info.getVersion() + "; failing!");
10013                    }
10014
10015                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10016                    if (libPkg == null) {
10017                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10018                                "Package " + packageName + " requires unavailable static shared"
10019                                        + " library; failing!");
10020                    }
10021
10022                    String expectedCertDigest = requiredCertDigests[i];
10023                    String libCertDigest = PackageUtils.computeCertSha256Digest(
10024                                libPkg.mSignatures[0]);
10025                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
10026                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10027                                "Package " + packageName + " requires differently signed" +
10028                                        " static shared library; failing!");
10029                    }
10030                }
10031
10032                if (outUsedLibraries == null) {
10033                    outUsedLibraries = new ArraySet<>();
10034                }
10035                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10036            }
10037        }
10038        return outUsedLibraries;
10039    }
10040
10041    private static boolean hasString(List<String> list, List<String> which) {
10042        if (list == null) {
10043            return false;
10044        }
10045        for (int i=list.size()-1; i>=0; i--) {
10046            for (int j=which.size()-1; j>=0; j--) {
10047                if (which.get(j).equals(list.get(i))) {
10048                    return true;
10049                }
10050            }
10051        }
10052        return false;
10053    }
10054
10055    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10056            PackageParser.Package changingPkg) {
10057        ArrayList<PackageParser.Package> res = null;
10058        for (PackageParser.Package pkg : mPackages.values()) {
10059            if (changingPkg != null
10060                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10061                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10062                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10063                            changingPkg.staticSharedLibName)) {
10064                return null;
10065            }
10066            if (res == null) {
10067                res = new ArrayList<>();
10068            }
10069            res.add(pkg);
10070            try {
10071                updateSharedLibrariesLPr(pkg, changingPkg);
10072            } catch (PackageManagerException e) {
10073                // If a system app update or an app and a required lib missing we
10074                // delete the package and for updated system apps keep the data as
10075                // it is better for the user to reinstall than to be in an limbo
10076                // state. Also libs disappearing under an app should never happen
10077                // - just in case.
10078                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10079                    final int flags = pkg.isUpdatedSystemApp()
10080                            ? PackageManager.DELETE_KEEP_DATA : 0;
10081                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10082                            flags , null, true, null);
10083                }
10084                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10085            }
10086        }
10087        return res;
10088    }
10089
10090    /**
10091     * Derive the value of the {@code cpuAbiOverride} based on the provided
10092     * value and an optional stored value from the package settings.
10093     */
10094    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10095        String cpuAbiOverride = null;
10096
10097        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10098            cpuAbiOverride = null;
10099        } else if (abiOverride != null) {
10100            cpuAbiOverride = abiOverride;
10101        } else if (settings != null) {
10102            cpuAbiOverride = settings.cpuAbiOverrideString;
10103        }
10104
10105        return cpuAbiOverride;
10106    }
10107
10108    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10109            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10110                    throws PackageManagerException {
10111        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10112        // If the package has children and this is the first dive in the function
10113        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10114        // whether all packages (parent and children) would be successfully scanned
10115        // before the actual scan since scanning mutates internal state and we want
10116        // to atomically install the package and its children.
10117        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10118            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10119                scanFlags |= SCAN_CHECK_ONLY;
10120            }
10121        } else {
10122            scanFlags &= ~SCAN_CHECK_ONLY;
10123        }
10124
10125        final PackageParser.Package scannedPkg;
10126        try {
10127            // Scan the parent
10128            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10129            // Scan the children
10130            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10131            for (int i = 0; i < childCount; i++) {
10132                PackageParser.Package childPkg = pkg.childPackages.get(i);
10133                scanPackageLI(childPkg, policyFlags,
10134                        scanFlags, currentTime, user);
10135            }
10136        } finally {
10137            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10138        }
10139
10140        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10141            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10142        }
10143
10144        return scannedPkg;
10145    }
10146
10147    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10148            int scanFlags, long currentTime, @Nullable UserHandle user)
10149                    throws PackageManagerException {
10150        boolean success = false;
10151        try {
10152            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10153                    currentTime, user);
10154            success = true;
10155            return res;
10156        } finally {
10157            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10158                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10159                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10160                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10161                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10162            }
10163        }
10164    }
10165
10166    /**
10167     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10168     */
10169    private static boolean apkHasCode(String fileName) {
10170        StrictJarFile jarFile = null;
10171        try {
10172            jarFile = new StrictJarFile(fileName,
10173                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10174            return jarFile.findEntry("classes.dex") != null;
10175        } catch (IOException ignore) {
10176        } finally {
10177            try {
10178                if (jarFile != null) {
10179                    jarFile.close();
10180                }
10181            } catch (IOException ignore) {}
10182        }
10183        return false;
10184    }
10185
10186    /**
10187     * Enforces code policy for the package. This ensures that if an APK has
10188     * declared hasCode="true" in its manifest that the APK actually contains
10189     * code.
10190     *
10191     * @throws PackageManagerException If bytecode could not be found when it should exist
10192     */
10193    private static void assertCodePolicy(PackageParser.Package pkg)
10194            throws PackageManagerException {
10195        final boolean shouldHaveCode =
10196                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10197        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10198            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10199                    "Package " + pkg.baseCodePath + " code is missing");
10200        }
10201
10202        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10203            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10204                final boolean splitShouldHaveCode =
10205                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10206                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10207                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10208                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10209                }
10210            }
10211        }
10212    }
10213
10214    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10215            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10216                    throws PackageManagerException {
10217        if (DEBUG_PACKAGE_SCANNING) {
10218            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10219                Log.d(TAG, "Scanning package " + pkg.packageName);
10220        }
10221
10222        applyPolicy(pkg, policyFlags);
10223
10224        assertPackageIsValid(pkg, policyFlags, scanFlags);
10225
10226        // Initialize package source and resource directories
10227        final File scanFile = new File(pkg.codePath);
10228        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10229        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10230
10231        SharedUserSetting suid = null;
10232        PackageSetting pkgSetting = null;
10233
10234        // Getting the package setting may have a side-effect, so if we
10235        // are only checking if scan would succeed, stash a copy of the
10236        // old setting to restore at the end.
10237        PackageSetting nonMutatedPs = null;
10238
10239        // We keep references to the derived CPU Abis from settings in oder to reuse
10240        // them in the case where we're not upgrading or booting for the first time.
10241        String primaryCpuAbiFromSettings = null;
10242        String secondaryCpuAbiFromSettings = null;
10243
10244        // writer
10245        synchronized (mPackages) {
10246            if (pkg.mSharedUserId != null) {
10247                // SIDE EFFECTS; may potentially allocate a new shared user
10248                suid = mSettings.getSharedUserLPw(
10249                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10250                if (DEBUG_PACKAGE_SCANNING) {
10251                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10252                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10253                                + "): packages=" + suid.packages);
10254                }
10255            }
10256
10257            // Check if we are renaming from an original package name.
10258            PackageSetting origPackage = null;
10259            String realName = null;
10260            if (pkg.mOriginalPackages != null) {
10261                // This package may need to be renamed to a previously
10262                // installed name.  Let's check on that...
10263                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10264                if (pkg.mOriginalPackages.contains(renamed)) {
10265                    // This package had originally been installed as the
10266                    // original name, and we have already taken care of
10267                    // transitioning to the new one.  Just update the new
10268                    // one to continue using the old name.
10269                    realName = pkg.mRealPackage;
10270                    if (!pkg.packageName.equals(renamed)) {
10271                        // Callers into this function may have already taken
10272                        // care of renaming the package; only do it here if
10273                        // it is not already done.
10274                        pkg.setPackageName(renamed);
10275                    }
10276                } else {
10277                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10278                        if ((origPackage = mSettings.getPackageLPr(
10279                                pkg.mOriginalPackages.get(i))) != null) {
10280                            // We do have the package already installed under its
10281                            // original name...  should we use it?
10282                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10283                                // New package is not compatible with original.
10284                                origPackage = null;
10285                                continue;
10286                            } else if (origPackage.sharedUser != null) {
10287                                // Make sure uid is compatible between packages.
10288                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10289                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10290                                            + " to " + pkg.packageName + ": old uid "
10291                                            + origPackage.sharedUser.name
10292                                            + " differs from " + pkg.mSharedUserId);
10293                                    origPackage = null;
10294                                    continue;
10295                                }
10296                                // TODO: Add case when shared user id is added [b/28144775]
10297                            } else {
10298                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10299                                        + pkg.packageName + " to old name " + origPackage.name);
10300                            }
10301                            break;
10302                        }
10303                    }
10304                }
10305            }
10306
10307            if (mTransferedPackages.contains(pkg.packageName)) {
10308                Slog.w(TAG, "Package " + pkg.packageName
10309                        + " was transferred to another, but its .apk remains");
10310            }
10311
10312            // See comments in nonMutatedPs declaration
10313            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10314                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10315                if (foundPs != null) {
10316                    nonMutatedPs = new PackageSetting(foundPs);
10317                }
10318            }
10319
10320            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10321                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10322                if (foundPs != null) {
10323                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10324                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10325                }
10326            }
10327
10328            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10329            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10330                PackageManagerService.reportSettingsProblem(Log.WARN,
10331                        "Package " + pkg.packageName + " shared user changed from "
10332                                + (pkgSetting.sharedUser != null
10333                                        ? pkgSetting.sharedUser.name : "<nothing>")
10334                                + " to "
10335                                + (suid != null ? suid.name : "<nothing>")
10336                                + "; replacing with new");
10337                pkgSetting = null;
10338            }
10339            final PackageSetting oldPkgSetting =
10340                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10341            final PackageSetting disabledPkgSetting =
10342                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10343
10344            String[] usesStaticLibraries = null;
10345            if (pkg.usesStaticLibraries != null) {
10346                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10347                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10348            }
10349
10350            if (pkgSetting == null) {
10351                final String parentPackageName = (pkg.parentPackage != null)
10352                        ? pkg.parentPackage.packageName : null;
10353                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10354                // REMOVE SharedUserSetting from method; update in a separate call
10355                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10356                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10357                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10358                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10359                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10360                        true /*allowInstall*/, instantApp, parentPackageName,
10361                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
10362                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10363                // SIDE EFFECTS; updates system state; move elsewhere
10364                if (origPackage != null) {
10365                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10366                }
10367                mSettings.addUserToSettingLPw(pkgSetting);
10368            } else {
10369                // REMOVE SharedUserSetting from method; update in a separate call.
10370                //
10371                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10372                // secondaryCpuAbi are not known at this point so we always update them
10373                // to null here, only to reset them at a later point.
10374                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10375                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10376                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10377                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10378                        UserManagerService.getInstance(), usesStaticLibraries,
10379                        pkg.usesStaticLibrariesVersions);
10380            }
10381            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10382            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10383
10384            // SIDE EFFECTS; modifies system state; move elsewhere
10385            if (pkgSetting.origPackage != null) {
10386                // If we are first transitioning from an original package,
10387                // fix up the new package's name now.  We need to do this after
10388                // looking up the package under its new name, so getPackageLP
10389                // can take care of fiddling things correctly.
10390                pkg.setPackageName(origPackage.name);
10391
10392                // File a report about this.
10393                String msg = "New package " + pkgSetting.realName
10394                        + " renamed to replace old package " + pkgSetting.name;
10395                reportSettingsProblem(Log.WARN, msg);
10396
10397                // Make a note of it.
10398                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10399                    mTransferedPackages.add(origPackage.name);
10400                }
10401
10402                // No longer need to retain this.
10403                pkgSetting.origPackage = null;
10404            }
10405
10406            // SIDE EFFECTS; modifies system state; move elsewhere
10407            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10408                // Make a note of it.
10409                mTransferedPackages.add(pkg.packageName);
10410            }
10411
10412            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10413                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10414            }
10415
10416            if ((scanFlags & SCAN_BOOTING) == 0
10417                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10418                // Check all shared libraries and map to their actual file path.
10419                // We only do this here for apps not on a system dir, because those
10420                // are the only ones that can fail an install due to this.  We
10421                // will take care of the system apps by updating all of their
10422                // library paths after the scan is done. Also during the initial
10423                // scan don't update any libs as we do this wholesale after all
10424                // apps are scanned to avoid dependency based scanning.
10425                updateSharedLibrariesLPr(pkg, null);
10426            }
10427
10428            if (mFoundPolicyFile) {
10429                SELinuxMMAC.assignSeInfoValue(pkg);
10430            }
10431            pkg.applicationInfo.uid = pkgSetting.appId;
10432            pkg.mExtras = pkgSetting;
10433
10434
10435            // Static shared libs have same package with different versions where
10436            // we internally use a synthetic package name to allow multiple versions
10437            // of the same package, therefore we need to compare signatures against
10438            // the package setting for the latest library version.
10439            PackageSetting signatureCheckPs = pkgSetting;
10440            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10441                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10442                if (libraryEntry != null) {
10443                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10444                }
10445            }
10446
10447            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10448                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10449                    // We just determined the app is signed correctly, so bring
10450                    // over the latest parsed certs.
10451                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10452                } else {
10453                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10454                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10455                                "Package " + pkg.packageName + " upgrade keys do not match the "
10456                                + "previously installed version");
10457                    } else {
10458                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10459                        String msg = "System package " + pkg.packageName
10460                                + " signature changed; retaining data.";
10461                        reportSettingsProblem(Log.WARN, msg);
10462                    }
10463                }
10464            } else {
10465                try {
10466                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10467                    verifySignaturesLP(signatureCheckPs, pkg);
10468                    // We just determined the app is signed correctly, so bring
10469                    // over the latest parsed certs.
10470                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10471                } catch (PackageManagerException e) {
10472                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10473                        throw e;
10474                    }
10475                    // The signature has changed, but this package is in the system
10476                    // image...  let's recover!
10477                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10478                    // However...  if this package is part of a shared user, but it
10479                    // doesn't match the signature of the shared user, let's fail.
10480                    // What this means is that you can't change the signatures
10481                    // associated with an overall shared user, which doesn't seem all
10482                    // that unreasonable.
10483                    if (signatureCheckPs.sharedUser != null) {
10484                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10485                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10486                            throw new PackageManagerException(
10487                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10488                                    "Signature mismatch for shared user: "
10489                                            + pkgSetting.sharedUser);
10490                        }
10491                    }
10492                    // File a report about this.
10493                    String msg = "System package " + pkg.packageName
10494                            + " signature changed; retaining data.";
10495                    reportSettingsProblem(Log.WARN, msg);
10496                }
10497            }
10498
10499            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10500                // This package wants to adopt ownership of permissions from
10501                // another package.
10502                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10503                    final String origName = pkg.mAdoptPermissions.get(i);
10504                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10505                    if (orig != null) {
10506                        if (verifyPackageUpdateLPr(orig, pkg)) {
10507                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10508                                    + pkg.packageName);
10509                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10510                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10511                        }
10512                    }
10513                }
10514            }
10515        }
10516
10517        pkg.applicationInfo.processName = fixProcessName(
10518                pkg.applicationInfo.packageName,
10519                pkg.applicationInfo.processName);
10520
10521        if (pkg != mPlatformPackage) {
10522            // Get all of our default paths setup
10523            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10524        }
10525
10526        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10527
10528        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10529            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10530                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10531                final boolean extractNativeLibs = !pkg.isLibrary();
10532                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10533                        mAppLib32InstallDir);
10534                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10535
10536                // Some system apps still use directory structure for native libraries
10537                // in which case we might end up not detecting abi solely based on apk
10538                // structure. Try to detect abi based on directory structure.
10539                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10540                        pkg.applicationInfo.primaryCpuAbi == null) {
10541                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10542                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10543                }
10544            } else {
10545                // This is not a first boot or an upgrade, don't bother deriving the
10546                // ABI during the scan. Instead, trust the value that was stored in the
10547                // package setting.
10548                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10549                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10550
10551                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10552
10553                if (DEBUG_ABI_SELECTION) {
10554                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10555                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10556                        pkg.applicationInfo.secondaryCpuAbi);
10557                }
10558            }
10559        } else {
10560            if ((scanFlags & SCAN_MOVE) != 0) {
10561                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10562                // but we already have this packages package info in the PackageSetting. We just
10563                // use that and derive the native library path based on the new codepath.
10564                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10565                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10566            }
10567
10568            // Set native library paths again. For moves, the path will be updated based on the
10569            // ABIs we've determined above. For non-moves, the path will be updated based on the
10570            // ABIs we determined during compilation, but the path will depend on the final
10571            // package path (after the rename away from the stage path).
10572            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10573        }
10574
10575        // This is a special case for the "system" package, where the ABI is
10576        // dictated by the zygote configuration (and init.rc). We should keep track
10577        // of this ABI so that we can deal with "normal" applications that run under
10578        // the same UID correctly.
10579        if (mPlatformPackage == pkg) {
10580            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10581                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10582        }
10583
10584        // If there's a mismatch between the abi-override in the package setting
10585        // and the abiOverride specified for the install. Warn about this because we
10586        // would've already compiled the app without taking the package setting into
10587        // account.
10588        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10589            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10590                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10591                        " for package " + pkg.packageName);
10592            }
10593        }
10594
10595        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10596        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10597        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10598
10599        // Copy the derived override back to the parsed package, so that we can
10600        // update the package settings accordingly.
10601        pkg.cpuAbiOverride = cpuAbiOverride;
10602
10603        if (DEBUG_ABI_SELECTION) {
10604            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10605                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10606                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10607        }
10608
10609        // Push the derived path down into PackageSettings so we know what to
10610        // clean up at uninstall time.
10611        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10612
10613        if (DEBUG_ABI_SELECTION) {
10614            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10615                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10616                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10617        }
10618
10619        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10620        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10621            // We don't do this here during boot because we can do it all
10622            // at once after scanning all existing packages.
10623            //
10624            // We also do this *before* we perform dexopt on this package, so that
10625            // we can avoid redundant dexopts, and also to make sure we've got the
10626            // code and package path correct.
10627            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10628        }
10629
10630        if (mFactoryTest && pkg.requestedPermissions.contains(
10631                android.Manifest.permission.FACTORY_TEST)) {
10632            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10633        }
10634
10635        if (isSystemApp(pkg)) {
10636            pkgSetting.isOrphaned = true;
10637        }
10638
10639        // Take care of first install / last update times.
10640        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10641        if (currentTime != 0) {
10642            if (pkgSetting.firstInstallTime == 0) {
10643                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10644            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10645                pkgSetting.lastUpdateTime = currentTime;
10646            }
10647        } else if (pkgSetting.firstInstallTime == 0) {
10648            // We need *something*.  Take time time stamp of the file.
10649            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10650        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10651            if (scanFileTime != pkgSetting.timeStamp) {
10652                // A package on the system image has changed; consider this
10653                // to be an update.
10654                pkgSetting.lastUpdateTime = scanFileTime;
10655            }
10656        }
10657        pkgSetting.setTimeStamp(scanFileTime);
10658
10659        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10660            if (nonMutatedPs != null) {
10661                synchronized (mPackages) {
10662                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10663                }
10664            }
10665        } else {
10666            final int userId = user == null ? 0 : user.getIdentifier();
10667            // Modify state for the given package setting
10668            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10669                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10670            if (pkgSetting.getInstantApp(userId)) {
10671                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10672            }
10673        }
10674        return pkg;
10675    }
10676
10677    /**
10678     * Applies policy to the parsed package based upon the given policy flags.
10679     * Ensures the package is in a good state.
10680     * <p>
10681     * Implementation detail: This method must NOT have any side effect. It would
10682     * ideally be static, but, it requires locks to read system state.
10683     */
10684    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10685        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10686            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10687            if (pkg.applicationInfo.isDirectBootAware()) {
10688                // we're direct boot aware; set for all components
10689                for (PackageParser.Service s : pkg.services) {
10690                    s.info.encryptionAware = s.info.directBootAware = true;
10691                }
10692                for (PackageParser.Provider p : pkg.providers) {
10693                    p.info.encryptionAware = p.info.directBootAware = true;
10694                }
10695                for (PackageParser.Activity a : pkg.activities) {
10696                    a.info.encryptionAware = a.info.directBootAware = true;
10697                }
10698                for (PackageParser.Activity r : pkg.receivers) {
10699                    r.info.encryptionAware = r.info.directBootAware = true;
10700                }
10701            }
10702        } else {
10703            // Only allow system apps to be flagged as core apps.
10704            pkg.coreApp = false;
10705            // clear flags not applicable to regular apps
10706            pkg.applicationInfo.privateFlags &=
10707                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10708            pkg.applicationInfo.privateFlags &=
10709                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10710        }
10711        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10712
10713        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10714            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10715        }
10716
10717        if (!isSystemApp(pkg)) {
10718            // Only system apps can use these features.
10719            pkg.mOriginalPackages = null;
10720            pkg.mRealPackage = null;
10721            pkg.mAdoptPermissions = null;
10722        }
10723    }
10724
10725    /**
10726     * Asserts the parsed package is valid according to the given policy. If the
10727     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10728     * <p>
10729     * Implementation detail: This method must NOT have any side effects. It would
10730     * ideally be static, but, it requires locks to read system state.
10731     *
10732     * @throws PackageManagerException If the package fails any of the validation checks
10733     */
10734    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10735            throws PackageManagerException {
10736        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10737            assertCodePolicy(pkg);
10738        }
10739
10740        if (pkg.applicationInfo.getCodePath() == null ||
10741                pkg.applicationInfo.getResourcePath() == null) {
10742            // Bail out. The resource and code paths haven't been set.
10743            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10744                    "Code and resource paths haven't been set correctly");
10745        }
10746
10747        // Make sure we're not adding any bogus keyset info
10748        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10749        ksms.assertScannedPackageValid(pkg);
10750
10751        synchronized (mPackages) {
10752            // The special "android" package can only be defined once
10753            if (pkg.packageName.equals("android")) {
10754                if (mAndroidApplication != null) {
10755                    Slog.w(TAG, "*************************************************");
10756                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10757                    Slog.w(TAG, " codePath=" + pkg.codePath);
10758                    Slog.w(TAG, "*************************************************");
10759                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10760                            "Core android package being redefined.  Skipping.");
10761                }
10762            }
10763
10764            // A package name must be unique; don't allow duplicates
10765            if (mPackages.containsKey(pkg.packageName)) {
10766                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10767                        "Application package " + pkg.packageName
10768                        + " already installed.  Skipping duplicate.");
10769            }
10770
10771            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10772                // Static libs have a synthetic package name containing the version
10773                // but we still want the base name to be unique.
10774                if (mPackages.containsKey(pkg.manifestPackageName)) {
10775                    throw new PackageManagerException(
10776                            "Duplicate static shared lib provider package");
10777                }
10778
10779                // Static shared libraries should have at least O target SDK
10780                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10781                    throw new PackageManagerException(
10782                            "Packages declaring static-shared libs must target O SDK or higher");
10783                }
10784
10785                // Package declaring static a shared lib cannot be instant apps
10786                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10787                    throw new PackageManagerException(
10788                            "Packages declaring static-shared libs cannot be instant apps");
10789                }
10790
10791                // Package declaring static a shared lib cannot be renamed since the package
10792                // name is synthetic and apps can't code around package manager internals.
10793                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10794                    throw new PackageManagerException(
10795                            "Packages declaring static-shared libs cannot be renamed");
10796                }
10797
10798                // Package declaring static a shared lib cannot declare child packages
10799                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10800                    throw new PackageManagerException(
10801                            "Packages declaring static-shared libs cannot have child packages");
10802                }
10803
10804                // Package declaring static a shared lib cannot declare dynamic libs
10805                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10806                    throw new PackageManagerException(
10807                            "Packages declaring static-shared libs cannot declare dynamic libs");
10808                }
10809
10810                // Package declaring static a shared lib cannot declare shared users
10811                if (pkg.mSharedUserId != null) {
10812                    throw new PackageManagerException(
10813                            "Packages declaring static-shared libs cannot declare shared users");
10814                }
10815
10816                // Static shared libs cannot declare activities
10817                if (!pkg.activities.isEmpty()) {
10818                    throw new PackageManagerException(
10819                            "Static shared libs cannot declare activities");
10820                }
10821
10822                // Static shared libs cannot declare services
10823                if (!pkg.services.isEmpty()) {
10824                    throw new PackageManagerException(
10825                            "Static shared libs cannot declare services");
10826                }
10827
10828                // Static shared libs cannot declare providers
10829                if (!pkg.providers.isEmpty()) {
10830                    throw new PackageManagerException(
10831                            "Static shared libs cannot declare content providers");
10832                }
10833
10834                // Static shared libs cannot declare receivers
10835                if (!pkg.receivers.isEmpty()) {
10836                    throw new PackageManagerException(
10837                            "Static shared libs cannot declare broadcast receivers");
10838                }
10839
10840                // Static shared libs cannot declare permission groups
10841                if (!pkg.permissionGroups.isEmpty()) {
10842                    throw new PackageManagerException(
10843                            "Static shared libs cannot declare permission groups");
10844                }
10845
10846                // Static shared libs cannot declare permissions
10847                if (!pkg.permissions.isEmpty()) {
10848                    throw new PackageManagerException(
10849                            "Static shared libs cannot declare permissions");
10850                }
10851
10852                // Static shared libs cannot declare protected broadcasts
10853                if (pkg.protectedBroadcasts != null) {
10854                    throw new PackageManagerException(
10855                            "Static shared libs cannot declare protected broadcasts");
10856                }
10857
10858                // Static shared libs cannot be overlay targets
10859                if (pkg.mOverlayTarget != null) {
10860                    throw new PackageManagerException(
10861                            "Static shared libs cannot be overlay targets");
10862                }
10863
10864                // The version codes must be ordered as lib versions
10865                int minVersionCode = Integer.MIN_VALUE;
10866                int maxVersionCode = Integer.MAX_VALUE;
10867
10868                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10869                        pkg.staticSharedLibName);
10870                if (versionedLib != null) {
10871                    final int versionCount = versionedLib.size();
10872                    for (int i = 0; i < versionCount; i++) {
10873                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10874                        final int libVersionCode = libInfo.getDeclaringPackage()
10875                                .getVersionCode();
10876                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10877                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10878                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10879                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10880                        } else {
10881                            minVersionCode = maxVersionCode = libVersionCode;
10882                            break;
10883                        }
10884                    }
10885                }
10886                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10887                    throw new PackageManagerException("Static shared"
10888                            + " lib version codes must be ordered as lib versions");
10889                }
10890            }
10891
10892            // Only privileged apps and updated privileged apps can add child packages.
10893            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10894                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10895                    throw new PackageManagerException("Only privileged apps can add child "
10896                            + "packages. Ignoring package " + pkg.packageName);
10897                }
10898                final int childCount = pkg.childPackages.size();
10899                for (int i = 0; i < childCount; i++) {
10900                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10901                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10902                            childPkg.packageName)) {
10903                        throw new PackageManagerException("Can't override child of "
10904                                + "another disabled app. Ignoring package " + pkg.packageName);
10905                    }
10906                }
10907            }
10908
10909            // If we're only installing presumed-existing packages, require that the
10910            // scanned APK is both already known and at the path previously established
10911            // for it.  Previously unknown packages we pick up normally, but if we have an
10912            // a priori expectation about this package's install presence, enforce it.
10913            // With a singular exception for new system packages. When an OTA contains
10914            // a new system package, we allow the codepath to change from a system location
10915            // to the user-installed location. If we don't allow this change, any newer,
10916            // user-installed version of the application will be ignored.
10917            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10918                if (mExpectingBetter.containsKey(pkg.packageName)) {
10919                    logCriticalInfo(Log.WARN,
10920                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10921                } else {
10922                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10923                    if (known != null) {
10924                        if (DEBUG_PACKAGE_SCANNING) {
10925                            Log.d(TAG, "Examining " + pkg.codePath
10926                                    + " and requiring known paths " + known.codePathString
10927                                    + " & " + known.resourcePathString);
10928                        }
10929                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10930                                || !pkg.applicationInfo.getResourcePath().equals(
10931                                        known.resourcePathString)) {
10932                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10933                                    "Application package " + pkg.packageName
10934                                    + " found at " + pkg.applicationInfo.getCodePath()
10935                                    + " but expected at " + known.codePathString
10936                                    + "; ignoring.");
10937                        }
10938                    }
10939                }
10940            }
10941
10942            // Verify that this new package doesn't have any content providers
10943            // that conflict with existing packages.  Only do this if the
10944            // package isn't already installed, since we don't want to break
10945            // things that are installed.
10946            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10947                final int N = pkg.providers.size();
10948                int i;
10949                for (i=0; i<N; i++) {
10950                    PackageParser.Provider p = pkg.providers.get(i);
10951                    if (p.info.authority != null) {
10952                        String names[] = p.info.authority.split(";");
10953                        for (int j = 0; j < names.length; j++) {
10954                            if (mProvidersByAuthority.containsKey(names[j])) {
10955                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10956                                final String otherPackageName =
10957                                        ((other != null && other.getComponentName() != null) ?
10958                                                other.getComponentName().getPackageName() : "?");
10959                                throw new PackageManagerException(
10960                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10961                                        "Can't install because provider name " + names[j]
10962                                                + " (in package " + pkg.applicationInfo.packageName
10963                                                + ") is already used by " + otherPackageName);
10964                            }
10965                        }
10966                    }
10967                }
10968            }
10969        }
10970    }
10971
10972    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10973            int type, String declaringPackageName, int declaringVersionCode) {
10974        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10975        if (versionedLib == null) {
10976            versionedLib = new SparseArray<>();
10977            mSharedLibraries.put(name, versionedLib);
10978            if (type == SharedLibraryInfo.TYPE_STATIC) {
10979                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10980            }
10981        } else if (versionedLib.indexOfKey(version) >= 0) {
10982            return false;
10983        }
10984        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10985                version, type, declaringPackageName, declaringVersionCode);
10986        versionedLib.put(version, libEntry);
10987        return true;
10988    }
10989
10990    private boolean removeSharedLibraryLPw(String name, int version) {
10991        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10992        if (versionedLib == null) {
10993            return false;
10994        }
10995        final int libIdx = versionedLib.indexOfKey(version);
10996        if (libIdx < 0) {
10997            return false;
10998        }
10999        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11000        versionedLib.remove(version);
11001        if (versionedLib.size() <= 0) {
11002            mSharedLibraries.remove(name);
11003            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11004                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11005                        .getPackageName());
11006            }
11007        }
11008        return true;
11009    }
11010
11011    /**
11012     * Adds a scanned package to the system. When this method is finished, the package will
11013     * be available for query, resolution, etc...
11014     */
11015    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11016            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11017        final String pkgName = pkg.packageName;
11018        if (mCustomResolverComponentName != null &&
11019                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11020            setUpCustomResolverActivity(pkg);
11021        }
11022
11023        if (pkg.packageName.equals("android")) {
11024            synchronized (mPackages) {
11025                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11026                    // Set up information for our fall-back user intent resolution activity.
11027                    mPlatformPackage = pkg;
11028                    pkg.mVersionCode = mSdkVersion;
11029                    mAndroidApplication = pkg.applicationInfo;
11030                    if (!mResolverReplaced) {
11031                        mResolveActivity.applicationInfo = mAndroidApplication;
11032                        mResolveActivity.name = ResolverActivity.class.getName();
11033                        mResolveActivity.packageName = mAndroidApplication.packageName;
11034                        mResolveActivity.processName = "system:ui";
11035                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11036                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11037                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11038                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11039                        mResolveActivity.exported = true;
11040                        mResolveActivity.enabled = true;
11041                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11042                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11043                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11044                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11045                                | ActivityInfo.CONFIG_ORIENTATION
11046                                | ActivityInfo.CONFIG_KEYBOARD
11047                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11048                        mResolveInfo.activityInfo = mResolveActivity;
11049                        mResolveInfo.priority = 0;
11050                        mResolveInfo.preferredOrder = 0;
11051                        mResolveInfo.match = 0;
11052                        mResolveComponentName = new ComponentName(
11053                                mAndroidApplication.packageName, mResolveActivity.name);
11054                    }
11055                }
11056            }
11057        }
11058
11059        ArrayList<PackageParser.Package> clientLibPkgs = null;
11060        // writer
11061        synchronized (mPackages) {
11062            boolean hasStaticSharedLibs = false;
11063
11064            // Any app can add new static shared libraries
11065            if (pkg.staticSharedLibName != null) {
11066                // Static shared libs don't allow renaming as they have synthetic package
11067                // names to allow install of multiple versions, so use name from manifest.
11068                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11069                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11070                        pkg.manifestPackageName, pkg.mVersionCode)) {
11071                    hasStaticSharedLibs = true;
11072                } else {
11073                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11074                                + pkg.staticSharedLibName + " already exists; skipping");
11075                }
11076                // Static shared libs cannot be updated once installed since they
11077                // use synthetic package name which includes the version code, so
11078                // not need to update other packages's shared lib dependencies.
11079            }
11080
11081            if (!hasStaticSharedLibs
11082                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11083                // Only system apps can add new dynamic shared libraries.
11084                if (pkg.libraryNames != null) {
11085                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11086                        String name = pkg.libraryNames.get(i);
11087                        boolean allowed = false;
11088                        if (pkg.isUpdatedSystemApp()) {
11089                            // New library entries can only be added through the
11090                            // system image.  This is important to get rid of a lot
11091                            // of nasty edge cases: for example if we allowed a non-
11092                            // system update of the app to add a library, then uninstalling
11093                            // the update would make the library go away, and assumptions
11094                            // we made such as through app install filtering would now
11095                            // have allowed apps on the device which aren't compatible
11096                            // with it.  Better to just have the restriction here, be
11097                            // conservative, and create many fewer cases that can negatively
11098                            // impact the user experience.
11099                            final PackageSetting sysPs = mSettings
11100                                    .getDisabledSystemPkgLPr(pkg.packageName);
11101                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11102                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11103                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11104                                        allowed = true;
11105                                        break;
11106                                    }
11107                                }
11108                            }
11109                        } else {
11110                            allowed = true;
11111                        }
11112                        if (allowed) {
11113                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11114                                    SharedLibraryInfo.VERSION_UNDEFINED,
11115                                    SharedLibraryInfo.TYPE_DYNAMIC,
11116                                    pkg.packageName, pkg.mVersionCode)) {
11117                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11118                                        + name + " already exists; skipping");
11119                            }
11120                        } else {
11121                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11122                                    + name + " that is not declared on system image; skipping");
11123                        }
11124                    }
11125
11126                    if ((scanFlags & SCAN_BOOTING) == 0) {
11127                        // If we are not booting, we need to update any applications
11128                        // that are clients of our shared library.  If we are booting,
11129                        // this will all be done once the scan is complete.
11130                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11131                    }
11132                }
11133            }
11134        }
11135
11136        if ((scanFlags & SCAN_BOOTING) != 0) {
11137            // No apps can run during boot scan, so they don't need to be frozen
11138        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11139            // Caller asked to not kill app, so it's probably not frozen
11140        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11141            // Caller asked us to ignore frozen check for some reason; they
11142            // probably didn't know the package name
11143        } else {
11144            // We're doing major surgery on this package, so it better be frozen
11145            // right now to keep it from launching
11146            checkPackageFrozen(pkgName);
11147        }
11148
11149        // Also need to kill any apps that are dependent on the library.
11150        if (clientLibPkgs != null) {
11151            for (int i=0; i<clientLibPkgs.size(); i++) {
11152                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11153                killApplication(clientPkg.applicationInfo.packageName,
11154                        clientPkg.applicationInfo.uid, "update lib");
11155            }
11156        }
11157
11158        // writer
11159        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11160
11161        synchronized (mPackages) {
11162            // We don't expect installation to fail beyond this point
11163
11164            // Add the new setting to mSettings
11165            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11166            // Add the new setting to mPackages
11167            mPackages.put(pkg.applicationInfo.packageName, pkg);
11168            // Make sure we don't accidentally delete its data.
11169            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11170            while (iter.hasNext()) {
11171                PackageCleanItem item = iter.next();
11172                if (pkgName.equals(item.packageName)) {
11173                    iter.remove();
11174                }
11175            }
11176
11177            // Add the package's KeySets to the global KeySetManagerService
11178            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11179            ksms.addScannedPackageLPw(pkg);
11180
11181            int N = pkg.providers.size();
11182            StringBuilder r = null;
11183            int i;
11184            for (i=0; i<N; i++) {
11185                PackageParser.Provider p = pkg.providers.get(i);
11186                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11187                        p.info.processName);
11188                mProviders.addProvider(p);
11189                p.syncable = p.info.isSyncable;
11190                if (p.info.authority != null) {
11191                    String names[] = p.info.authority.split(";");
11192                    p.info.authority = null;
11193                    for (int j = 0; j < names.length; j++) {
11194                        if (j == 1 && p.syncable) {
11195                            // We only want the first authority for a provider to possibly be
11196                            // syncable, so if we already added this provider using a different
11197                            // authority clear the syncable flag. We copy the provider before
11198                            // changing it because the mProviders object contains a reference
11199                            // to a provider that we don't want to change.
11200                            // Only do this for the second authority since the resulting provider
11201                            // object can be the same for all future authorities for this provider.
11202                            p = new PackageParser.Provider(p);
11203                            p.syncable = false;
11204                        }
11205                        if (!mProvidersByAuthority.containsKey(names[j])) {
11206                            mProvidersByAuthority.put(names[j], p);
11207                            if (p.info.authority == null) {
11208                                p.info.authority = names[j];
11209                            } else {
11210                                p.info.authority = p.info.authority + ";" + names[j];
11211                            }
11212                            if (DEBUG_PACKAGE_SCANNING) {
11213                                if (chatty)
11214                                    Log.d(TAG, "Registered content provider: " + names[j]
11215                                            + ", className = " + p.info.name + ", isSyncable = "
11216                                            + p.info.isSyncable);
11217                            }
11218                        } else {
11219                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11220                            Slog.w(TAG, "Skipping provider name " + names[j] +
11221                                    " (in package " + pkg.applicationInfo.packageName +
11222                                    "): name already used by "
11223                                    + ((other != null && other.getComponentName() != null)
11224                                            ? other.getComponentName().getPackageName() : "?"));
11225                        }
11226                    }
11227                }
11228                if (chatty) {
11229                    if (r == null) {
11230                        r = new StringBuilder(256);
11231                    } else {
11232                        r.append(' ');
11233                    }
11234                    r.append(p.info.name);
11235                }
11236            }
11237            if (r != null) {
11238                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11239            }
11240
11241            N = pkg.services.size();
11242            r = null;
11243            for (i=0; i<N; i++) {
11244                PackageParser.Service s = pkg.services.get(i);
11245                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11246                        s.info.processName);
11247                mServices.addService(s);
11248                if (chatty) {
11249                    if (r == null) {
11250                        r = new StringBuilder(256);
11251                    } else {
11252                        r.append(' ');
11253                    }
11254                    r.append(s.info.name);
11255                }
11256            }
11257            if (r != null) {
11258                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11259            }
11260
11261            N = pkg.receivers.size();
11262            r = null;
11263            for (i=0; i<N; i++) {
11264                PackageParser.Activity a = pkg.receivers.get(i);
11265                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11266                        a.info.processName);
11267                mReceivers.addActivity(a, "receiver");
11268                if (chatty) {
11269                    if (r == null) {
11270                        r = new StringBuilder(256);
11271                    } else {
11272                        r.append(' ');
11273                    }
11274                    r.append(a.info.name);
11275                }
11276            }
11277            if (r != null) {
11278                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11279            }
11280
11281            N = pkg.activities.size();
11282            r = null;
11283            for (i=0; i<N; i++) {
11284                PackageParser.Activity a = pkg.activities.get(i);
11285                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11286                        a.info.processName);
11287                mActivities.addActivity(a, "activity");
11288                if (chatty) {
11289                    if (r == null) {
11290                        r = new StringBuilder(256);
11291                    } else {
11292                        r.append(' ');
11293                    }
11294                    r.append(a.info.name);
11295                }
11296            }
11297            if (r != null) {
11298                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11299            }
11300
11301            N = pkg.permissionGroups.size();
11302            r = null;
11303            for (i=0; i<N; i++) {
11304                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11305                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11306                final String curPackageName = cur == null ? null : cur.info.packageName;
11307                // Dont allow ephemeral apps to define new permission groups.
11308                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11309                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11310                            + pg.info.packageName
11311                            + " ignored: instant apps cannot define new permission groups.");
11312                    continue;
11313                }
11314                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11315                if (cur == null || isPackageUpdate) {
11316                    mPermissionGroups.put(pg.info.name, pg);
11317                    if (chatty) {
11318                        if (r == null) {
11319                            r = new StringBuilder(256);
11320                        } else {
11321                            r.append(' ');
11322                        }
11323                        if (isPackageUpdate) {
11324                            r.append("UPD:");
11325                        }
11326                        r.append(pg.info.name);
11327                    }
11328                } else {
11329                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11330                            + pg.info.packageName + " ignored: original from "
11331                            + cur.info.packageName);
11332                    if (chatty) {
11333                        if (r == null) {
11334                            r = new StringBuilder(256);
11335                        } else {
11336                            r.append(' ');
11337                        }
11338                        r.append("DUP:");
11339                        r.append(pg.info.name);
11340                    }
11341                }
11342            }
11343            if (r != null) {
11344                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11345            }
11346
11347            N = pkg.permissions.size();
11348            r = null;
11349            for (i=0; i<N; i++) {
11350                PackageParser.Permission p = pkg.permissions.get(i);
11351
11352                // Dont allow ephemeral apps to define new permissions.
11353                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11354                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11355                            + p.info.packageName
11356                            + " ignored: instant apps cannot define new permissions.");
11357                    continue;
11358                }
11359
11360                // Assume by default that we did not install this permission into the system.
11361                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11362
11363                // Now that permission groups have a special meaning, we ignore permission
11364                // groups for legacy apps to prevent unexpected behavior. In particular,
11365                // permissions for one app being granted to someone just because they happen
11366                // to be in a group defined by another app (before this had no implications).
11367                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11368                    p.group = mPermissionGroups.get(p.info.group);
11369                    // Warn for a permission in an unknown group.
11370                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11371                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11372                                + p.info.packageName + " in an unknown group " + p.info.group);
11373                    }
11374                }
11375
11376                ArrayMap<String, BasePermission> permissionMap =
11377                        p.tree ? mSettings.mPermissionTrees
11378                                : mSettings.mPermissions;
11379                BasePermission bp = permissionMap.get(p.info.name);
11380
11381                // Allow system apps to redefine non-system permissions
11382                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11383                    final boolean currentOwnerIsSystem = (bp.perm != null
11384                            && isSystemApp(bp.perm.owner));
11385                    if (isSystemApp(p.owner)) {
11386                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11387                            // It's a built-in permission and no owner, take ownership now
11388                            bp.packageSetting = pkgSetting;
11389                            bp.perm = p;
11390                            bp.uid = pkg.applicationInfo.uid;
11391                            bp.sourcePackage = p.info.packageName;
11392                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11393                        } else if (!currentOwnerIsSystem) {
11394                            String msg = "New decl " + p.owner + " of permission  "
11395                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11396                            reportSettingsProblem(Log.WARN, msg);
11397                            bp = null;
11398                        }
11399                    }
11400                }
11401
11402                if (bp == null) {
11403                    bp = new BasePermission(p.info.name, p.info.packageName,
11404                            BasePermission.TYPE_NORMAL);
11405                    permissionMap.put(p.info.name, bp);
11406                }
11407
11408                if (bp.perm == null) {
11409                    if (bp.sourcePackage == null
11410                            || bp.sourcePackage.equals(p.info.packageName)) {
11411                        BasePermission tree = findPermissionTreeLP(p.info.name);
11412                        if (tree == null
11413                                || tree.sourcePackage.equals(p.info.packageName)) {
11414                            bp.packageSetting = pkgSetting;
11415                            bp.perm = p;
11416                            bp.uid = pkg.applicationInfo.uid;
11417                            bp.sourcePackage = p.info.packageName;
11418                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11419                            if (chatty) {
11420                                if (r == null) {
11421                                    r = new StringBuilder(256);
11422                                } else {
11423                                    r.append(' ');
11424                                }
11425                                r.append(p.info.name);
11426                            }
11427                        } else {
11428                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11429                                    + p.info.packageName + " ignored: base tree "
11430                                    + tree.name + " is from package "
11431                                    + tree.sourcePackage);
11432                        }
11433                    } else {
11434                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11435                                + p.info.packageName + " ignored: original from "
11436                                + bp.sourcePackage);
11437                    }
11438                } else if (chatty) {
11439                    if (r == null) {
11440                        r = new StringBuilder(256);
11441                    } else {
11442                        r.append(' ');
11443                    }
11444                    r.append("DUP:");
11445                    r.append(p.info.name);
11446                }
11447                if (bp.perm == p) {
11448                    bp.protectionLevel = p.info.protectionLevel;
11449                }
11450            }
11451
11452            if (r != null) {
11453                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11454            }
11455
11456            N = pkg.instrumentation.size();
11457            r = null;
11458            for (i=0; i<N; i++) {
11459                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11460                a.info.packageName = pkg.applicationInfo.packageName;
11461                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11462                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11463                a.info.splitNames = pkg.splitNames;
11464                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11465                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11466                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11467                a.info.dataDir = pkg.applicationInfo.dataDir;
11468                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11469                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11470                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11471                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11472                mInstrumentation.put(a.getComponentName(), a);
11473                if (chatty) {
11474                    if (r == null) {
11475                        r = new StringBuilder(256);
11476                    } else {
11477                        r.append(' ');
11478                    }
11479                    r.append(a.info.name);
11480                }
11481            }
11482            if (r != null) {
11483                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11484            }
11485
11486            if (pkg.protectedBroadcasts != null) {
11487                N = pkg.protectedBroadcasts.size();
11488                synchronized (mProtectedBroadcasts) {
11489                    for (i = 0; i < N; i++) {
11490                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11491                    }
11492                }
11493            }
11494        }
11495
11496        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11497    }
11498
11499    /**
11500     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11501     * is derived purely on the basis of the contents of {@code scanFile} and
11502     * {@code cpuAbiOverride}.
11503     *
11504     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11505     */
11506    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11507                                 String cpuAbiOverride, boolean extractLibs,
11508                                 File appLib32InstallDir)
11509            throws PackageManagerException {
11510        // Give ourselves some initial paths; we'll come back for another
11511        // pass once we've determined ABI below.
11512        setNativeLibraryPaths(pkg, appLib32InstallDir);
11513
11514        // We would never need to extract libs for forward-locked and external packages,
11515        // since the container service will do it for us. We shouldn't attempt to
11516        // extract libs from system app when it was not updated.
11517        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11518                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11519            extractLibs = false;
11520        }
11521
11522        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11523        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11524
11525        NativeLibraryHelper.Handle handle = null;
11526        try {
11527            handle = NativeLibraryHelper.Handle.create(pkg);
11528            // TODO(multiArch): This can be null for apps that didn't go through the
11529            // usual installation process. We can calculate it again, like we
11530            // do during install time.
11531            //
11532            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11533            // unnecessary.
11534            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11535
11536            // Null out the abis so that they can be recalculated.
11537            pkg.applicationInfo.primaryCpuAbi = null;
11538            pkg.applicationInfo.secondaryCpuAbi = null;
11539            if (isMultiArch(pkg.applicationInfo)) {
11540                // Warn if we've set an abiOverride for multi-lib packages..
11541                // By definition, we need to copy both 32 and 64 bit libraries for
11542                // such packages.
11543                if (pkg.cpuAbiOverride != null
11544                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11545                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11546                }
11547
11548                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11549                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11550                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11551                    if (extractLibs) {
11552                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11553                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11554                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11555                                useIsaSpecificSubdirs);
11556                    } else {
11557                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11558                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11559                    }
11560                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11561                }
11562
11563                // Shared library native code should be in the APK zip aligned
11564                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11565                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11566                            "Shared library native lib extraction not supported");
11567                }
11568
11569                maybeThrowExceptionForMultiArchCopy(
11570                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11571
11572                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11573                    if (extractLibs) {
11574                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11575                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11576                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11577                                useIsaSpecificSubdirs);
11578                    } else {
11579                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11580                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11581                    }
11582                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11583                }
11584
11585                maybeThrowExceptionForMultiArchCopy(
11586                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11587
11588                if (abi64 >= 0) {
11589                    // Shared library native libs should be in the APK zip aligned
11590                    if (extractLibs && pkg.isLibrary()) {
11591                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11592                                "Shared library native lib extraction not supported");
11593                    }
11594                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11595                }
11596
11597                if (abi32 >= 0) {
11598                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11599                    if (abi64 >= 0) {
11600                        if (pkg.use32bitAbi) {
11601                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11602                            pkg.applicationInfo.primaryCpuAbi = abi;
11603                        } else {
11604                            pkg.applicationInfo.secondaryCpuAbi = abi;
11605                        }
11606                    } else {
11607                        pkg.applicationInfo.primaryCpuAbi = abi;
11608                    }
11609                }
11610            } else {
11611                String[] abiList = (cpuAbiOverride != null) ?
11612                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11613
11614                // Enable gross and lame hacks for apps that are built with old
11615                // SDK tools. We must scan their APKs for renderscript bitcode and
11616                // not launch them if it's present. Don't bother checking on devices
11617                // that don't have 64 bit support.
11618                boolean needsRenderScriptOverride = false;
11619                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11620                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11621                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11622                    needsRenderScriptOverride = true;
11623                }
11624
11625                final int copyRet;
11626                if (extractLibs) {
11627                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11628                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11629                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11630                } else {
11631                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11632                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11633                }
11634                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11635
11636                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11637                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11638                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11639                }
11640
11641                if (copyRet >= 0) {
11642                    // Shared libraries that have native libs must be multi-architecture
11643                    if (pkg.isLibrary()) {
11644                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11645                                "Shared library with native libs must be multiarch");
11646                    }
11647                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11648                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11649                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11650                } else if (needsRenderScriptOverride) {
11651                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11652                }
11653            }
11654        } catch (IOException ioe) {
11655            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11656        } finally {
11657            IoUtils.closeQuietly(handle);
11658        }
11659
11660        // Now that we've calculated the ABIs and determined if it's an internal app,
11661        // we will go ahead and populate the nativeLibraryPath.
11662        setNativeLibraryPaths(pkg, appLib32InstallDir);
11663    }
11664
11665    /**
11666     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11667     * i.e, so that all packages can be run inside a single process if required.
11668     *
11669     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11670     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11671     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11672     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11673     * updating a package that belongs to a shared user.
11674     *
11675     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11676     * adds unnecessary complexity.
11677     */
11678    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11679            PackageParser.Package scannedPackage) {
11680        String requiredInstructionSet = null;
11681        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11682            requiredInstructionSet = VMRuntime.getInstructionSet(
11683                     scannedPackage.applicationInfo.primaryCpuAbi);
11684        }
11685
11686        PackageSetting requirer = null;
11687        for (PackageSetting ps : packagesForUser) {
11688            // If packagesForUser contains scannedPackage, we skip it. This will happen
11689            // when scannedPackage is an update of an existing package. Without this check,
11690            // we will never be able to change the ABI of any package belonging to a shared
11691            // user, even if it's compatible with other packages.
11692            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11693                if (ps.primaryCpuAbiString == null) {
11694                    continue;
11695                }
11696
11697                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11698                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11699                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11700                    // this but there's not much we can do.
11701                    String errorMessage = "Instruction set mismatch, "
11702                            + ((requirer == null) ? "[caller]" : requirer)
11703                            + " requires " + requiredInstructionSet + " whereas " + ps
11704                            + " requires " + instructionSet;
11705                    Slog.w(TAG, errorMessage);
11706                }
11707
11708                if (requiredInstructionSet == null) {
11709                    requiredInstructionSet = instructionSet;
11710                    requirer = ps;
11711                }
11712            }
11713        }
11714
11715        if (requiredInstructionSet != null) {
11716            String adjustedAbi;
11717            if (requirer != null) {
11718                // requirer != null implies that either scannedPackage was null or that scannedPackage
11719                // did not require an ABI, in which case we have to adjust scannedPackage to match
11720                // the ABI of the set (which is the same as requirer's ABI)
11721                adjustedAbi = requirer.primaryCpuAbiString;
11722                if (scannedPackage != null) {
11723                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11724                }
11725            } else {
11726                // requirer == null implies that we're updating all ABIs in the set to
11727                // match scannedPackage.
11728                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11729            }
11730
11731            for (PackageSetting ps : packagesForUser) {
11732                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11733                    if (ps.primaryCpuAbiString != null) {
11734                        continue;
11735                    }
11736
11737                    ps.primaryCpuAbiString = adjustedAbi;
11738                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11739                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11740                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11741                        if (DEBUG_ABI_SELECTION) {
11742                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11743                                    + " (requirer="
11744                                    + (requirer != null ? requirer.pkg : "null")
11745                                    + ", scannedPackage="
11746                                    + (scannedPackage != null ? scannedPackage : "null")
11747                                    + ")");
11748                        }
11749                        try {
11750                            mInstaller.rmdex(ps.codePathString,
11751                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11752                        } catch (InstallerException ignored) {
11753                        }
11754                    }
11755                }
11756            }
11757        }
11758    }
11759
11760    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11761        synchronized (mPackages) {
11762            mResolverReplaced = true;
11763            // Set up information for custom user intent resolution activity.
11764            mResolveActivity.applicationInfo = pkg.applicationInfo;
11765            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11766            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11767            mResolveActivity.processName = pkg.applicationInfo.packageName;
11768            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11769            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11770                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11771            mResolveActivity.theme = 0;
11772            mResolveActivity.exported = true;
11773            mResolveActivity.enabled = true;
11774            mResolveInfo.activityInfo = mResolveActivity;
11775            mResolveInfo.priority = 0;
11776            mResolveInfo.preferredOrder = 0;
11777            mResolveInfo.match = 0;
11778            mResolveComponentName = mCustomResolverComponentName;
11779            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11780                    mResolveComponentName);
11781        }
11782    }
11783
11784    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11785        if (installerActivity == null) {
11786            if (DEBUG_EPHEMERAL) {
11787                Slog.d(TAG, "Clear ephemeral installer activity");
11788            }
11789            mInstantAppInstallerActivity = null;
11790            return;
11791        }
11792
11793        if (DEBUG_EPHEMERAL) {
11794            Slog.d(TAG, "Set ephemeral installer activity: "
11795                    + installerActivity.getComponentName());
11796        }
11797        // Set up information for ephemeral installer activity
11798        mInstantAppInstallerActivity = installerActivity;
11799        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11800                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11801        mInstantAppInstallerActivity.exported = true;
11802        mInstantAppInstallerActivity.enabled = true;
11803        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11804        mInstantAppInstallerInfo.priority = 0;
11805        mInstantAppInstallerInfo.preferredOrder = 1;
11806        mInstantAppInstallerInfo.isDefault = true;
11807        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11808                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11809    }
11810
11811    private static String calculateBundledApkRoot(final String codePathString) {
11812        final File codePath = new File(codePathString);
11813        final File codeRoot;
11814        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11815            codeRoot = Environment.getRootDirectory();
11816        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11817            codeRoot = Environment.getOemDirectory();
11818        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11819            codeRoot = Environment.getVendorDirectory();
11820        } else {
11821            // Unrecognized code path; take its top real segment as the apk root:
11822            // e.g. /something/app/blah.apk => /something
11823            try {
11824                File f = codePath.getCanonicalFile();
11825                File parent = f.getParentFile();    // non-null because codePath is a file
11826                File tmp;
11827                while ((tmp = parent.getParentFile()) != null) {
11828                    f = parent;
11829                    parent = tmp;
11830                }
11831                codeRoot = f;
11832                Slog.w(TAG, "Unrecognized code path "
11833                        + codePath + " - using " + codeRoot);
11834            } catch (IOException e) {
11835                // Can't canonicalize the code path -- shenanigans?
11836                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11837                return Environment.getRootDirectory().getPath();
11838            }
11839        }
11840        return codeRoot.getPath();
11841    }
11842
11843    /**
11844     * Derive and set the location of native libraries for the given package,
11845     * which varies depending on where and how the package was installed.
11846     */
11847    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11848        final ApplicationInfo info = pkg.applicationInfo;
11849        final String codePath = pkg.codePath;
11850        final File codeFile = new File(codePath);
11851        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11852        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11853
11854        info.nativeLibraryRootDir = null;
11855        info.nativeLibraryRootRequiresIsa = false;
11856        info.nativeLibraryDir = null;
11857        info.secondaryNativeLibraryDir = null;
11858
11859        if (isApkFile(codeFile)) {
11860            // Monolithic install
11861            if (bundledApp) {
11862                // If "/system/lib64/apkname" exists, assume that is the per-package
11863                // native library directory to use; otherwise use "/system/lib/apkname".
11864                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11865                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11866                        getPrimaryInstructionSet(info));
11867
11868                // This is a bundled system app so choose the path based on the ABI.
11869                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11870                // is just the default path.
11871                final String apkName = deriveCodePathName(codePath);
11872                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11873                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11874                        apkName).getAbsolutePath();
11875
11876                if (info.secondaryCpuAbi != null) {
11877                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11878                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11879                            secondaryLibDir, apkName).getAbsolutePath();
11880                }
11881            } else if (asecApp) {
11882                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11883                        .getAbsolutePath();
11884            } else {
11885                final String apkName = deriveCodePathName(codePath);
11886                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11887                        .getAbsolutePath();
11888            }
11889
11890            info.nativeLibraryRootRequiresIsa = false;
11891            info.nativeLibraryDir = info.nativeLibraryRootDir;
11892        } else {
11893            // Cluster install
11894            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11895            info.nativeLibraryRootRequiresIsa = true;
11896
11897            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11898                    getPrimaryInstructionSet(info)).getAbsolutePath();
11899
11900            if (info.secondaryCpuAbi != null) {
11901                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11902                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11903            }
11904        }
11905    }
11906
11907    /**
11908     * Calculate the abis and roots for a bundled app. These can uniquely
11909     * be determined from the contents of the system partition, i.e whether
11910     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11911     * of this information, and instead assume that the system was built
11912     * sensibly.
11913     */
11914    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11915                                           PackageSetting pkgSetting) {
11916        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11917
11918        // If "/system/lib64/apkname" exists, assume that is the per-package
11919        // native library directory to use; otherwise use "/system/lib/apkname".
11920        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11921        setBundledAppAbi(pkg, apkRoot, apkName);
11922        // pkgSetting might be null during rescan following uninstall of updates
11923        // to a bundled app, so accommodate that possibility.  The settings in
11924        // that case will be established later from the parsed package.
11925        //
11926        // If the settings aren't null, sync them up with what we've just derived.
11927        // note that apkRoot isn't stored in the package settings.
11928        if (pkgSetting != null) {
11929            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11930            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11931        }
11932    }
11933
11934    /**
11935     * Deduces the ABI of a bundled app and sets the relevant fields on the
11936     * parsed pkg object.
11937     *
11938     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11939     *        under which system libraries are installed.
11940     * @param apkName the name of the installed package.
11941     */
11942    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11943        final File codeFile = new File(pkg.codePath);
11944
11945        final boolean has64BitLibs;
11946        final boolean has32BitLibs;
11947        if (isApkFile(codeFile)) {
11948            // Monolithic install
11949            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11950            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11951        } else {
11952            // Cluster install
11953            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11954            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11955                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11956                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11957                has64BitLibs = (new File(rootDir, isa)).exists();
11958            } else {
11959                has64BitLibs = false;
11960            }
11961            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11962                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11963                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11964                has32BitLibs = (new File(rootDir, isa)).exists();
11965            } else {
11966                has32BitLibs = false;
11967            }
11968        }
11969
11970        if (has64BitLibs && !has32BitLibs) {
11971            // The package has 64 bit libs, but not 32 bit libs. Its primary
11972            // ABI should be 64 bit. We can safely assume here that the bundled
11973            // native libraries correspond to the most preferred ABI in the list.
11974
11975            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11976            pkg.applicationInfo.secondaryCpuAbi = null;
11977        } else if (has32BitLibs && !has64BitLibs) {
11978            // The package has 32 bit libs but not 64 bit libs. Its primary
11979            // ABI should be 32 bit.
11980
11981            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11982            pkg.applicationInfo.secondaryCpuAbi = null;
11983        } else if (has32BitLibs && has64BitLibs) {
11984            // The application has both 64 and 32 bit bundled libraries. We check
11985            // here that the app declares multiArch support, and warn if it doesn't.
11986            //
11987            // We will be lenient here and record both ABIs. The primary will be the
11988            // ABI that's higher on the list, i.e, a device that's configured to prefer
11989            // 64 bit apps will see a 64 bit primary ABI,
11990
11991            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11992                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11993            }
11994
11995            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11996                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11997                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11998            } else {
11999                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12000                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12001            }
12002        } else {
12003            pkg.applicationInfo.primaryCpuAbi = null;
12004            pkg.applicationInfo.secondaryCpuAbi = null;
12005        }
12006    }
12007
12008    private void killApplication(String pkgName, int appId, String reason) {
12009        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12010    }
12011
12012    private void killApplication(String pkgName, int appId, int userId, String reason) {
12013        // Request the ActivityManager to kill the process(only for existing packages)
12014        // so that we do not end up in a confused state while the user is still using the older
12015        // version of the application while the new one gets installed.
12016        final long token = Binder.clearCallingIdentity();
12017        try {
12018            IActivityManager am = ActivityManager.getService();
12019            if (am != null) {
12020                try {
12021                    am.killApplication(pkgName, appId, userId, reason);
12022                } catch (RemoteException e) {
12023                }
12024            }
12025        } finally {
12026            Binder.restoreCallingIdentity(token);
12027        }
12028    }
12029
12030    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12031        // Remove the parent package setting
12032        PackageSetting ps = (PackageSetting) pkg.mExtras;
12033        if (ps != null) {
12034            removePackageLI(ps, chatty);
12035        }
12036        // Remove the child package setting
12037        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12038        for (int i = 0; i < childCount; i++) {
12039            PackageParser.Package childPkg = pkg.childPackages.get(i);
12040            ps = (PackageSetting) childPkg.mExtras;
12041            if (ps != null) {
12042                removePackageLI(ps, chatty);
12043            }
12044        }
12045    }
12046
12047    void removePackageLI(PackageSetting ps, boolean chatty) {
12048        if (DEBUG_INSTALL) {
12049            if (chatty)
12050                Log.d(TAG, "Removing package " + ps.name);
12051        }
12052
12053        // writer
12054        synchronized (mPackages) {
12055            mPackages.remove(ps.name);
12056            final PackageParser.Package pkg = ps.pkg;
12057            if (pkg != null) {
12058                cleanPackageDataStructuresLILPw(pkg, chatty);
12059            }
12060        }
12061    }
12062
12063    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12064        if (DEBUG_INSTALL) {
12065            if (chatty)
12066                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12067        }
12068
12069        // writer
12070        synchronized (mPackages) {
12071            // Remove the parent package
12072            mPackages.remove(pkg.applicationInfo.packageName);
12073            cleanPackageDataStructuresLILPw(pkg, chatty);
12074
12075            // Remove the child packages
12076            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12077            for (int i = 0; i < childCount; i++) {
12078                PackageParser.Package childPkg = pkg.childPackages.get(i);
12079                mPackages.remove(childPkg.applicationInfo.packageName);
12080                cleanPackageDataStructuresLILPw(childPkg, chatty);
12081            }
12082        }
12083    }
12084
12085    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12086        int N = pkg.providers.size();
12087        StringBuilder r = null;
12088        int i;
12089        for (i=0; i<N; i++) {
12090            PackageParser.Provider p = pkg.providers.get(i);
12091            mProviders.removeProvider(p);
12092            if (p.info.authority == null) {
12093
12094                /* There was another ContentProvider with this authority when
12095                 * this app was installed so this authority is null,
12096                 * Ignore it as we don't have to unregister the provider.
12097                 */
12098                continue;
12099            }
12100            String names[] = p.info.authority.split(";");
12101            for (int j = 0; j < names.length; j++) {
12102                if (mProvidersByAuthority.get(names[j]) == p) {
12103                    mProvidersByAuthority.remove(names[j]);
12104                    if (DEBUG_REMOVE) {
12105                        if (chatty)
12106                            Log.d(TAG, "Unregistered content provider: " + names[j]
12107                                    + ", className = " + p.info.name + ", isSyncable = "
12108                                    + p.info.isSyncable);
12109                    }
12110                }
12111            }
12112            if (DEBUG_REMOVE && chatty) {
12113                if (r == null) {
12114                    r = new StringBuilder(256);
12115                } else {
12116                    r.append(' ');
12117                }
12118                r.append(p.info.name);
12119            }
12120        }
12121        if (r != null) {
12122            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12123        }
12124
12125        N = pkg.services.size();
12126        r = null;
12127        for (i=0; i<N; i++) {
12128            PackageParser.Service s = pkg.services.get(i);
12129            mServices.removeService(s);
12130            if (chatty) {
12131                if (r == null) {
12132                    r = new StringBuilder(256);
12133                } else {
12134                    r.append(' ');
12135                }
12136                r.append(s.info.name);
12137            }
12138        }
12139        if (r != null) {
12140            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12141        }
12142
12143        N = pkg.receivers.size();
12144        r = null;
12145        for (i=0; i<N; i++) {
12146            PackageParser.Activity a = pkg.receivers.get(i);
12147            mReceivers.removeActivity(a, "receiver");
12148            if (DEBUG_REMOVE && chatty) {
12149                if (r == null) {
12150                    r = new StringBuilder(256);
12151                } else {
12152                    r.append(' ');
12153                }
12154                r.append(a.info.name);
12155            }
12156        }
12157        if (r != null) {
12158            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12159        }
12160
12161        N = pkg.activities.size();
12162        r = null;
12163        for (i=0; i<N; i++) {
12164            PackageParser.Activity a = pkg.activities.get(i);
12165            mActivities.removeActivity(a, "activity");
12166            if (DEBUG_REMOVE && chatty) {
12167                if (r == null) {
12168                    r = new StringBuilder(256);
12169                } else {
12170                    r.append(' ');
12171                }
12172                r.append(a.info.name);
12173            }
12174        }
12175        if (r != null) {
12176            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12177        }
12178
12179        N = pkg.permissions.size();
12180        r = null;
12181        for (i=0; i<N; i++) {
12182            PackageParser.Permission p = pkg.permissions.get(i);
12183            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12184            if (bp == null) {
12185                bp = mSettings.mPermissionTrees.get(p.info.name);
12186            }
12187            if (bp != null && bp.perm == p) {
12188                bp.perm = null;
12189                if (DEBUG_REMOVE && chatty) {
12190                    if (r == null) {
12191                        r = new StringBuilder(256);
12192                    } else {
12193                        r.append(' ');
12194                    }
12195                    r.append(p.info.name);
12196                }
12197            }
12198            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12199                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12200                if (appOpPkgs != null) {
12201                    appOpPkgs.remove(pkg.packageName);
12202                }
12203            }
12204        }
12205        if (r != null) {
12206            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12207        }
12208
12209        N = pkg.requestedPermissions.size();
12210        r = null;
12211        for (i=0; i<N; i++) {
12212            String perm = pkg.requestedPermissions.get(i);
12213            BasePermission bp = mSettings.mPermissions.get(perm);
12214            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12215                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12216                if (appOpPkgs != null) {
12217                    appOpPkgs.remove(pkg.packageName);
12218                    if (appOpPkgs.isEmpty()) {
12219                        mAppOpPermissionPackages.remove(perm);
12220                    }
12221                }
12222            }
12223        }
12224        if (r != null) {
12225            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12226        }
12227
12228        N = pkg.instrumentation.size();
12229        r = null;
12230        for (i=0; i<N; i++) {
12231            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12232            mInstrumentation.remove(a.getComponentName());
12233            if (DEBUG_REMOVE && chatty) {
12234                if (r == null) {
12235                    r = new StringBuilder(256);
12236                } else {
12237                    r.append(' ');
12238                }
12239                r.append(a.info.name);
12240            }
12241        }
12242        if (r != null) {
12243            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12244        }
12245
12246        r = null;
12247        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12248            // Only system apps can hold shared libraries.
12249            if (pkg.libraryNames != null) {
12250                for (i = 0; i < pkg.libraryNames.size(); i++) {
12251                    String name = pkg.libraryNames.get(i);
12252                    if (removeSharedLibraryLPw(name, 0)) {
12253                        if (DEBUG_REMOVE && chatty) {
12254                            if (r == null) {
12255                                r = new StringBuilder(256);
12256                            } else {
12257                                r.append(' ');
12258                            }
12259                            r.append(name);
12260                        }
12261                    }
12262                }
12263            }
12264        }
12265
12266        r = null;
12267
12268        // Any package can hold static shared libraries.
12269        if (pkg.staticSharedLibName != null) {
12270            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12271                if (DEBUG_REMOVE && chatty) {
12272                    if (r == null) {
12273                        r = new StringBuilder(256);
12274                    } else {
12275                        r.append(' ');
12276                    }
12277                    r.append(pkg.staticSharedLibName);
12278                }
12279            }
12280        }
12281
12282        if (r != null) {
12283            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12284        }
12285    }
12286
12287    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12288        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12289            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12290                return true;
12291            }
12292        }
12293        return false;
12294    }
12295
12296    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12297    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12298    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12299
12300    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12301        // Update the parent permissions
12302        updatePermissionsLPw(pkg.packageName, pkg, flags);
12303        // Update the child permissions
12304        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12305        for (int i = 0; i < childCount; i++) {
12306            PackageParser.Package childPkg = pkg.childPackages.get(i);
12307            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12308        }
12309    }
12310
12311    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12312            int flags) {
12313        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12314        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12315    }
12316
12317    private void updatePermissionsLPw(String changingPkg,
12318            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12319        // Make sure there are no dangling permission trees.
12320        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12321        while (it.hasNext()) {
12322            final BasePermission bp = it.next();
12323            if (bp.packageSetting == null) {
12324                // We may not yet have parsed the package, so just see if
12325                // we still know about its settings.
12326                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12327            }
12328            if (bp.packageSetting == null) {
12329                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12330                        + " from package " + bp.sourcePackage);
12331                it.remove();
12332            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12333                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12334                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12335                            + " from package " + bp.sourcePackage);
12336                    flags |= UPDATE_PERMISSIONS_ALL;
12337                    it.remove();
12338                }
12339            }
12340        }
12341
12342        // Make sure all dynamic permissions have been assigned to a package,
12343        // and make sure there are no dangling permissions.
12344        it = mSettings.mPermissions.values().iterator();
12345        while (it.hasNext()) {
12346            final BasePermission bp = it.next();
12347            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12348                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12349                        + bp.name + " pkg=" + bp.sourcePackage
12350                        + " info=" + bp.pendingInfo);
12351                if (bp.packageSetting == null && bp.pendingInfo != null) {
12352                    final BasePermission tree = findPermissionTreeLP(bp.name);
12353                    if (tree != null && tree.perm != null) {
12354                        bp.packageSetting = tree.packageSetting;
12355                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12356                                new PermissionInfo(bp.pendingInfo));
12357                        bp.perm.info.packageName = tree.perm.info.packageName;
12358                        bp.perm.info.name = bp.name;
12359                        bp.uid = tree.uid;
12360                    }
12361                }
12362            }
12363            if (bp.packageSetting == null) {
12364                // We may not yet have parsed the package, so just see if
12365                // we still know about its settings.
12366                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12367            }
12368            if (bp.packageSetting == null) {
12369                Slog.w(TAG, "Removing dangling permission: " + bp.name
12370                        + " from package " + bp.sourcePackage);
12371                it.remove();
12372            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12373                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12374                    Slog.i(TAG, "Removing old permission: " + bp.name
12375                            + " from package " + bp.sourcePackage);
12376                    flags |= UPDATE_PERMISSIONS_ALL;
12377                    it.remove();
12378                }
12379            }
12380        }
12381
12382        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12383        // Now update the permissions for all packages, in particular
12384        // replace the granted permissions of the system packages.
12385        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12386            for (PackageParser.Package pkg : mPackages.values()) {
12387                if (pkg != pkgInfo) {
12388                    // Only replace for packages on requested volume
12389                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12390                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12391                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12392                    grantPermissionsLPw(pkg, replace, changingPkg);
12393                }
12394            }
12395        }
12396
12397        if (pkgInfo != null) {
12398            // Only replace for packages on requested volume
12399            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12400            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12401                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12402            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12403        }
12404        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12405    }
12406
12407    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12408            String packageOfInterest) {
12409        // IMPORTANT: There are two types of permissions: install and runtime.
12410        // Install time permissions are granted when the app is installed to
12411        // all device users and users added in the future. Runtime permissions
12412        // are granted at runtime explicitly to specific users. Normal and signature
12413        // protected permissions are install time permissions. Dangerous permissions
12414        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12415        // otherwise they are runtime permissions. This function does not manage
12416        // runtime permissions except for the case an app targeting Lollipop MR1
12417        // being upgraded to target a newer SDK, in which case dangerous permissions
12418        // are transformed from install time to runtime ones.
12419
12420        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12421        if (ps == null) {
12422            return;
12423        }
12424
12425        PermissionsState permissionsState = ps.getPermissionsState();
12426        PermissionsState origPermissions = permissionsState;
12427
12428        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12429
12430        boolean runtimePermissionsRevoked = false;
12431        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12432
12433        boolean changedInstallPermission = false;
12434
12435        if (replace) {
12436            ps.installPermissionsFixed = false;
12437            if (!ps.isSharedUser()) {
12438                origPermissions = new PermissionsState(permissionsState);
12439                permissionsState.reset();
12440            } else {
12441                // We need to know only about runtime permission changes since the
12442                // calling code always writes the install permissions state but
12443                // the runtime ones are written only if changed. The only cases of
12444                // changed runtime permissions here are promotion of an install to
12445                // runtime and revocation of a runtime from a shared user.
12446                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12447                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12448                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12449                    runtimePermissionsRevoked = true;
12450                }
12451            }
12452        }
12453
12454        permissionsState.setGlobalGids(mGlobalGids);
12455
12456        final int N = pkg.requestedPermissions.size();
12457        for (int i=0; i<N; i++) {
12458            final String name = pkg.requestedPermissions.get(i);
12459            final BasePermission bp = mSettings.mPermissions.get(name);
12460            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12461                    >= Build.VERSION_CODES.M;
12462
12463            if (DEBUG_INSTALL) {
12464                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12465            }
12466
12467            if (bp == null || bp.packageSetting == null) {
12468                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12469                    if (DEBUG_PERMISSIONS) {
12470                        Slog.i(TAG, "Unknown permission " + name
12471                                + " in package " + pkg.packageName);
12472                    }
12473                }
12474                continue;
12475            }
12476
12477
12478            // Limit ephemeral apps to ephemeral allowed permissions.
12479            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12480                if (DEBUG_PERMISSIONS) {
12481                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12482                            + pkg.packageName);
12483                }
12484                continue;
12485            }
12486
12487            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12488                if (DEBUG_PERMISSIONS) {
12489                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12490                            + pkg.packageName);
12491                }
12492                continue;
12493            }
12494
12495            final String perm = bp.name;
12496            boolean allowedSig = false;
12497            int grant = GRANT_DENIED;
12498
12499            // Keep track of app op permissions.
12500            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12501                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12502                if (pkgs == null) {
12503                    pkgs = new ArraySet<>();
12504                    mAppOpPermissionPackages.put(bp.name, pkgs);
12505                }
12506                pkgs.add(pkg.packageName);
12507            }
12508
12509            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12510            switch (level) {
12511                case PermissionInfo.PROTECTION_NORMAL: {
12512                    // For all apps normal permissions are install time ones.
12513                    grant = GRANT_INSTALL;
12514                } break;
12515
12516                case PermissionInfo.PROTECTION_DANGEROUS: {
12517                    // If a permission review is required for legacy apps we represent
12518                    // their permissions as always granted runtime ones since we need
12519                    // to keep the review required permission flag per user while an
12520                    // install permission's state is shared across all users.
12521                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12522                        // For legacy apps dangerous permissions are install time ones.
12523                        grant = GRANT_INSTALL;
12524                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12525                        // For legacy apps that became modern, install becomes runtime.
12526                        grant = GRANT_UPGRADE;
12527                    } else if (mPromoteSystemApps
12528                            && isSystemApp(ps)
12529                            && mExistingSystemPackages.contains(ps.name)) {
12530                        // For legacy system apps, install becomes runtime.
12531                        // We cannot check hasInstallPermission() for system apps since those
12532                        // permissions were granted implicitly and not persisted pre-M.
12533                        grant = GRANT_UPGRADE;
12534                    } else {
12535                        // For modern apps keep runtime permissions unchanged.
12536                        grant = GRANT_RUNTIME;
12537                    }
12538                } break;
12539
12540                case PermissionInfo.PROTECTION_SIGNATURE: {
12541                    // For all apps signature permissions are install time ones.
12542                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12543                    if (allowedSig) {
12544                        grant = GRANT_INSTALL;
12545                    }
12546                } break;
12547            }
12548
12549            if (DEBUG_PERMISSIONS) {
12550                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12551            }
12552
12553            if (grant != GRANT_DENIED) {
12554                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12555                    // If this is an existing, non-system package, then
12556                    // we can't add any new permissions to it.
12557                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12558                        // Except...  if this is a permission that was added
12559                        // to the platform (note: need to only do this when
12560                        // updating the platform).
12561                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12562                            grant = GRANT_DENIED;
12563                        }
12564                    }
12565                }
12566
12567                switch (grant) {
12568                    case GRANT_INSTALL: {
12569                        // Revoke this as runtime permission to handle the case of
12570                        // a runtime permission being downgraded to an install one.
12571                        // Also in permission review mode we keep dangerous permissions
12572                        // for legacy apps
12573                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12574                            if (origPermissions.getRuntimePermissionState(
12575                                    bp.name, userId) != null) {
12576                                // Revoke the runtime permission and clear the flags.
12577                                origPermissions.revokeRuntimePermission(bp, userId);
12578                                origPermissions.updatePermissionFlags(bp, userId,
12579                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12580                                // If we revoked a permission permission, we have to write.
12581                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12582                                        changedRuntimePermissionUserIds, userId);
12583                            }
12584                        }
12585                        // Grant an install permission.
12586                        if (permissionsState.grantInstallPermission(bp) !=
12587                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12588                            changedInstallPermission = true;
12589                        }
12590                    } break;
12591
12592                    case GRANT_RUNTIME: {
12593                        // Grant previously granted runtime permissions.
12594                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12595                            PermissionState permissionState = origPermissions
12596                                    .getRuntimePermissionState(bp.name, userId);
12597                            int flags = permissionState != null
12598                                    ? permissionState.getFlags() : 0;
12599                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12600                                // Don't propagate the permission in a permission review mode if
12601                                // the former was revoked, i.e. marked to not propagate on upgrade.
12602                                // Note that in a permission review mode install permissions are
12603                                // represented as constantly granted runtime ones since we need to
12604                                // keep a per user state associated with the permission. Also the
12605                                // revoke on upgrade flag is no longer applicable and is reset.
12606                                final boolean revokeOnUpgrade = (flags & PackageManager
12607                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12608                                if (revokeOnUpgrade) {
12609                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12610                                    // Since we changed the flags, we have to write.
12611                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12612                                            changedRuntimePermissionUserIds, userId);
12613                                }
12614                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12615                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12616                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12617                                        // If we cannot put the permission as it was,
12618                                        // we have to write.
12619                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12620                                                changedRuntimePermissionUserIds, userId);
12621                                    }
12622                                }
12623
12624                                // If the app supports runtime permissions no need for a review.
12625                                if (mPermissionReviewRequired
12626                                        && appSupportsRuntimePermissions
12627                                        && (flags & PackageManager
12628                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12629                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12630                                    // Since we changed the flags, we have to write.
12631                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12632                                            changedRuntimePermissionUserIds, userId);
12633                                }
12634                            } else if (mPermissionReviewRequired
12635                                    && !appSupportsRuntimePermissions) {
12636                                // For legacy apps that need a permission review, every new
12637                                // runtime permission is granted but it is pending a review.
12638                                // We also need to review only platform defined runtime
12639                                // permissions as these are the only ones the platform knows
12640                                // how to disable the API to simulate revocation as legacy
12641                                // apps don't expect to run with revoked permissions.
12642                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12643                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12644                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12645                                        // We changed the flags, hence have to write.
12646                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12647                                                changedRuntimePermissionUserIds, userId);
12648                                    }
12649                                }
12650                                if (permissionsState.grantRuntimePermission(bp, userId)
12651                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12652                                    // We changed the permission, hence have to write.
12653                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12654                                            changedRuntimePermissionUserIds, userId);
12655                                }
12656                            }
12657                            // Propagate the permission flags.
12658                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12659                        }
12660                    } break;
12661
12662                    case GRANT_UPGRADE: {
12663                        // Grant runtime permissions for a previously held install permission.
12664                        PermissionState permissionState = origPermissions
12665                                .getInstallPermissionState(bp.name);
12666                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12667
12668                        if (origPermissions.revokeInstallPermission(bp)
12669                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12670                            // We will be transferring the permission flags, so clear them.
12671                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12672                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12673                            changedInstallPermission = true;
12674                        }
12675
12676                        // If the permission is not to be promoted to runtime we ignore it and
12677                        // also its other flags as they are not applicable to install permissions.
12678                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12679                            for (int userId : currentUserIds) {
12680                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12681                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12682                                    // Transfer the permission flags.
12683                                    permissionsState.updatePermissionFlags(bp, userId,
12684                                            flags, flags);
12685                                    // If we granted the permission, we have to write.
12686                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12687                                            changedRuntimePermissionUserIds, userId);
12688                                }
12689                            }
12690                        }
12691                    } break;
12692
12693                    default: {
12694                        if (packageOfInterest == null
12695                                || packageOfInterest.equals(pkg.packageName)) {
12696                            if (DEBUG_PERMISSIONS) {
12697                                Slog.i(TAG, "Not granting permission " + perm
12698                                        + " to package " + pkg.packageName
12699                                        + " because it was previously installed without");
12700                            }
12701                        }
12702                    } break;
12703                }
12704            } else {
12705                if (permissionsState.revokeInstallPermission(bp) !=
12706                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12707                    // Also drop the permission flags.
12708                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12709                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12710                    changedInstallPermission = true;
12711                    Slog.i(TAG, "Un-granting permission " + perm
12712                            + " from package " + pkg.packageName
12713                            + " (protectionLevel=" + bp.protectionLevel
12714                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12715                            + ")");
12716                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
12717                    // Don't print warning for app op permissions, since it is fine for them
12718                    // not to be granted, there is a UI for the user to decide.
12719                    if (DEBUG_PERMISSIONS
12720                            && (packageOfInterest == null
12721                                    || packageOfInterest.equals(pkg.packageName))) {
12722                        Slog.i(TAG, "Not granting permission " + perm
12723                                + " to package " + pkg.packageName
12724                                + " (protectionLevel=" + bp.protectionLevel
12725                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12726                                + ")");
12727                    }
12728                }
12729            }
12730        }
12731
12732        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12733                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12734            // This is the first that we have heard about this package, so the
12735            // permissions we have now selected are fixed until explicitly
12736            // changed.
12737            ps.installPermissionsFixed = true;
12738        }
12739
12740        // Persist the runtime permissions state for users with changes. If permissions
12741        // were revoked because no app in the shared user declares them we have to
12742        // write synchronously to avoid losing runtime permissions state.
12743        for (int userId : changedRuntimePermissionUserIds) {
12744            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12745        }
12746    }
12747
12748    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12749        boolean allowed = false;
12750        final int NP = PackageParser.NEW_PERMISSIONS.length;
12751        for (int ip=0; ip<NP; ip++) {
12752            final PackageParser.NewPermissionInfo npi
12753                    = PackageParser.NEW_PERMISSIONS[ip];
12754            if (npi.name.equals(perm)
12755                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12756                allowed = true;
12757                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12758                        + pkg.packageName);
12759                break;
12760            }
12761        }
12762        return allowed;
12763    }
12764
12765    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12766            BasePermission bp, PermissionsState origPermissions) {
12767        boolean privilegedPermission = (bp.protectionLevel
12768                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12769        boolean privappPermissionsDisable =
12770                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12771        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12772        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12773        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12774                && !platformPackage && platformPermission) {
12775            ArraySet<String> wlPermissions = SystemConfig.getInstance()
12776                    .getPrivAppPermissions(pkg.packageName);
12777            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12778            if (!whitelisted) {
12779                Slog.w(TAG, "Privileged permission " + perm + " for package "
12780                        + pkg.packageName + " - not in privapp-permissions whitelist");
12781                // Only report violations for apps on system image
12782                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12783                    if (mPrivappPermissionsViolations == null) {
12784                        mPrivappPermissionsViolations = new ArraySet<>();
12785                    }
12786                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12787                }
12788                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12789                    return false;
12790                }
12791            }
12792        }
12793        boolean allowed = (compareSignatures(
12794                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12795                        == PackageManager.SIGNATURE_MATCH)
12796                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12797                        == PackageManager.SIGNATURE_MATCH);
12798        if (!allowed && privilegedPermission) {
12799            if (isSystemApp(pkg)) {
12800                // For updated system applications, a system permission
12801                // is granted only if it had been defined by the original application.
12802                if (pkg.isUpdatedSystemApp()) {
12803                    final PackageSetting sysPs = mSettings
12804                            .getDisabledSystemPkgLPr(pkg.packageName);
12805                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12806                        // If the original was granted this permission, we take
12807                        // that grant decision as read and propagate it to the
12808                        // update.
12809                        if (sysPs.isPrivileged()) {
12810                            allowed = true;
12811                        }
12812                    } else {
12813                        // The system apk may have been updated with an older
12814                        // version of the one on the data partition, but which
12815                        // granted a new system permission that it didn't have
12816                        // before.  In this case we do want to allow the app to
12817                        // now get the new permission if the ancestral apk is
12818                        // privileged to get it.
12819                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
12820                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
12821                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
12822                                    allowed = true;
12823                                    break;
12824                                }
12825                            }
12826                        }
12827                        // Also if a privileged parent package on the system image or any of
12828                        // its children requested a privileged permission, the updated child
12829                        // packages can also get the permission.
12830                        if (pkg.parentPackage != null) {
12831                            final PackageSetting disabledSysParentPs = mSettings
12832                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12833                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
12834                                    && disabledSysParentPs.isPrivileged()) {
12835                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
12836                                    allowed = true;
12837                                } else if (disabledSysParentPs.pkg.childPackages != null) {
12838                                    final int count = disabledSysParentPs.pkg.childPackages.size();
12839                                    for (int i = 0; i < count; i++) {
12840                                        PackageParser.Package disabledSysChildPkg =
12841                                                disabledSysParentPs.pkg.childPackages.get(i);
12842                                        if (isPackageRequestingPermission(disabledSysChildPkg,
12843                                                perm)) {
12844                                            allowed = true;
12845                                            break;
12846                                        }
12847                                    }
12848                                }
12849                            }
12850                        }
12851                    }
12852                } else {
12853                    allowed = isPrivilegedApp(pkg);
12854                }
12855            }
12856        }
12857        if (!allowed) {
12858            if (!allowed && (bp.protectionLevel
12859                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
12860                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12861                // If this was a previously normal/dangerous permission that got moved
12862                // to a system permission as part of the runtime permission redesign, then
12863                // we still want to blindly grant it to old apps.
12864                allowed = true;
12865            }
12866            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
12867                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12868                // If this permission is to be granted to the system installer and
12869                // this app is an installer, then it gets the permission.
12870                allowed = true;
12871            }
12872            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
12873                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12874                // If this permission is to be granted to the system verifier and
12875                // this app is a verifier, then it gets the permission.
12876                allowed = true;
12877            }
12878            if (!allowed && (bp.protectionLevel
12879                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
12880                    && isSystemApp(pkg)) {
12881                // Any pre-installed system app is allowed to get this permission.
12882                allowed = true;
12883            }
12884            if (!allowed && (bp.protectionLevel
12885                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
12886                // For development permissions, a development permission
12887                // is granted only if it was already granted.
12888                allowed = origPermissions.hasInstallPermission(perm);
12889            }
12890            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
12891                    && pkg.packageName.equals(mSetupWizardPackage)) {
12892                // If this permission is to be granted to the system setup wizard and
12893                // this app is a setup wizard, then it gets the permission.
12894                allowed = true;
12895            }
12896        }
12897        return allowed;
12898    }
12899
12900    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12901        final int permCount = pkg.requestedPermissions.size();
12902        for (int j = 0; j < permCount; j++) {
12903            String requestedPermission = pkg.requestedPermissions.get(j);
12904            if (permission.equals(requestedPermission)) {
12905                return true;
12906            }
12907        }
12908        return false;
12909    }
12910
12911    final class ActivityIntentResolver
12912            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12913        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12914                boolean defaultOnly, int userId) {
12915            if (!sUserManager.exists(userId)) return null;
12916            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12917            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12918        }
12919
12920        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12921                int userId) {
12922            if (!sUserManager.exists(userId)) return null;
12923            mFlags = flags;
12924            return super.queryIntent(intent, resolvedType,
12925                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12926                    userId);
12927        }
12928
12929        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12930                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12931            if (!sUserManager.exists(userId)) return null;
12932            if (packageActivities == null) {
12933                return null;
12934            }
12935            mFlags = flags;
12936            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12937            final int N = packageActivities.size();
12938            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12939                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12940
12941            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12942            for (int i = 0; i < N; ++i) {
12943                intentFilters = packageActivities.get(i).intents;
12944                if (intentFilters != null && intentFilters.size() > 0) {
12945                    PackageParser.ActivityIntentInfo[] array =
12946                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12947                    intentFilters.toArray(array);
12948                    listCut.add(array);
12949                }
12950            }
12951            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12952        }
12953
12954        /**
12955         * Finds a privileged activity that matches the specified activity names.
12956         */
12957        private PackageParser.Activity findMatchingActivity(
12958                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12959            for (PackageParser.Activity sysActivity : activityList) {
12960                if (sysActivity.info.name.equals(activityInfo.name)) {
12961                    return sysActivity;
12962                }
12963                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12964                    return sysActivity;
12965                }
12966                if (sysActivity.info.targetActivity != null) {
12967                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12968                        return sysActivity;
12969                    }
12970                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12971                        return sysActivity;
12972                    }
12973                }
12974            }
12975            return null;
12976        }
12977
12978        public class IterGenerator<E> {
12979            public Iterator<E> generate(ActivityIntentInfo info) {
12980                return null;
12981            }
12982        }
12983
12984        public class ActionIterGenerator extends IterGenerator<String> {
12985            @Override
12986            public Iterator<String> generate(ActivityIntentInfo info) {
12987                return info.actionsIterator();
12988            }
12989        }
12990
12991        public class CategoriesIterGenerator extends IterGenerator<String> {
12992            @Override
12993            public Iterator<String> generate(ActivityIntentInfo info) {
12994                return info.categoriesIterator();
12995            }
12996        }
12997
12998        public class SchemesIterGenerator extends IterGenerator<String> {
12999            @Override
13000            public Iterator<String> generate(ActivityIntentInfo info) {
13001                return info.schemesIterator();
13002            }
13003        }
13004
13005        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13006            @Override
13007            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13008                return info.authoritiesIterator();
13009            }
13010        }
13011
13012        /**
13013         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13014         * MODIFIED. Do not pass in a list that should not be changed.
13015         */
13016        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13017                IterGenerator<T> generator, Iterator<T> searchIterator) {
13018            // loop through the set of actions; every one must be found in the intent filter
13019            while (searchIterator.hasNext()) {
13020                // we must have at least one filter in the list to consider a match
13021                if (intentList.size() == 0) {
13022                    break;
13023                }
13024
13025                final T searchAction = searchIterator.next();
13026
13027                // loop through the set of intent filters
13028                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13029                while (intentIter.hasNext()) {
13030                    final ActivityIntentInfo intentInfo = intentIter.next();
13031                    boolean selectionFound = false;
13032
13033                    // loop through the intent filter's selection criteria; at least one
13034                    // of them must match the searched criteria
13035                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13036                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13037                        final T intentSelection = intentSelectionIter.next();
13038                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13039                            selectionFound = true;
13040                            break;
13041                        }
13042                    }
13043
13044                    // the selection criteria wasn't found in this filter's set; this filter
13045                    // is not a potential match
13046                    if (!selectionFound) {
13047                        intentIter.remove();
13048                    }
13049                }
13050            }
13051        }
13052
13053        private boolean isProtectedAction(ActivityIntentInfo filter) {
13054            final Iterator<String> actionsIter = filter.actionsIterator();
13055            while (actionsIter != null && actionsIter.hasNext()) {
13056                final String filterAction = actionsIter.next();
13057                if (PROTECTED_ACTIONS.contains(filterAction)) {
13058                    return true;
13059                }
13060            }
13061            return false;
13062        }
13063
13064        /**
13065         * Adjusts the priority of the given intent filter according to policy.
13066         * <p>
13067         * <ul>
13068         * <li>The priority for non privileged applications is capped to '0'</li>
13069         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13070         * <li>The priority for unbundled updates to privileged applications is capped to the
13071         *      priority defined on the system partition</li>
13072         * </ul>
13073         * <p>
13074         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13075         * allowed to obtain any priority on any action.
13076         */
13077        private void adjustPriority(
13078                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13079            // nothing to do; priority is fine as-is
13080            if (intent.getPriority() <= 0) {
13081                return;
13082            }
13083
13084            final ActivityInfo activityInfo = intent.activity.info;
13085            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13086
13087            final boolean privilegedApp =
13088                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13089            if (!privilegedApp) {
13090                // non-privileged applications can never define a priority >0
13091                if (DEBUG_FILTERS) {
13092                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13093                            + " package: " + applicationInfo.packageName
13094                            + " activity: " + intent.activity.className
13095                            + " origPrio: " + intent.getPriority());
13096                }
13097                intent.setPriority(0);
13098                return;
13099            }
13100
13101            if (systemActivities == null) {
13102                // the system package is not disabled; we're parsing the system partition
13103                if (isProtectedAction(intent)) {
13104                    if (mDeferProtectedFilters) {
13105                        // We can't deal with these just yet. No component should ever obtain a
13106                        // >0 priority for a protected actions, with ONE exception -- the setup
13107                        // wizard. The setup wizard, however, cannot be known until we're able to
13108                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13109                        // until all intent filters have been processed. Chicken, meet egg.
13110                        // Let the filter temporarily have a high priority and rectify the
13111                        // priorities after all system packages have been scanned.
13112                        mProtectedFilters.add(intent);
13113                        if (DEBUG_FILTERS) {
13114                            Slog.i(TAG, "Protected action; save for later;"
13115                                    + " package: " + applicationInfo.packageName
13116                                    + " activity: " + intent.activity.className
13117                                    + " origPrio: " + intent.getPriority());
13118                        }
13119                        return;
13120                    } else {
13121                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13122                            Slog.i(TAG, "No setup wizard;"
13123                                + " All protected intents capped to priority 0");
13124                        }
13125                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13126                            if (DEBUG_FILTERS) {
13127                                Slog.i(TAG, "Found setup wizard;"
13128                                    + " allow priority " + intent.getPriority() + ";"
13129                                    + " package: " + intent.activity.info.packageName
13130                                    + " activity: " + intent.activity.className
13131                                    + " priority: " + intent.getPriority());
13132                            }
13133                            // setup wizard gets whatever it wants
13134                            return;
13135                        }
13136                        if (DEBUG_FILTERS) {
13137                            Slog.i(TAG, "Protected action; cap priority to 0;"
13138                                    + " package: " + intent.activity.info.packageName
13139                                    + " activity: " + intent.activity.className
13140                                    + " origPrio: " + intent.getPriority());
13141                        }
13142                        intent.setPriority(0);
13143                        return;
13144                    }
13145                }
13146                // privileged apps on the system image get whatever priority they request
13147                return;
13148            }
13149
13150            // privileged app unbundled update ... try to find the same activity
13151            final PackageParser.Activity foundActivity =
13152                    findMatchingActivity(systemActivities, activityInfo);
13153            if (foundActivity == null) {
13154                // this is a new activity; it cannot obtain >0 priority
13155                if (DEBUG_FILTERS) {
13156                    Slog.i(TAG, "New activity; cap priority to 0;"
13157                            + " package: " + applicationInfo.packageName
13158                            + " activity: " + intent.activity.className
13159                            + " origPrio: " + intent.getPriority());
13160                }
13161                intent.setPriority(0);
13162                return;
13163            }
13164
13165            // found activity, now check for filter equivalence
13166
13167            // a shallow copy is enough; we modify the list, not its contents
13168            final List<ActivityIntentInfo> intentListCopy =
13169                    new ArrayList<>(foundActivity.intents);
13170            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13171
13172            // find matching action subsets
13173            final Iterator<String> actionsIterator = intent.actionsIterator();
13174            if (actionsIterator != null) {
13175                getIntentListSubset(
13176                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13177                if (intentListCopy.size() == 0) {
13178                    // no more intents to match; we're not equivalent
13179                    if (DEBUG_FILTERS) {
13180                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13181                                + " package: " + applicationInfo.packageName
13182                                + " activity: " + intent.activity.className
13183                                + " origPrio: " + intent.getPriority());
13184                    }
13185                    intent.setPriority(0);
13186                    return;
13187                }
13188            }
13189
13190            // find matching category subsets
13191            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13192            if (categoriesIterator != null) {
13193                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13194                        categoriesIterator);
13195                if (intentListCopy.size() == 0) {
13196                    // no more intents to match; we're not equivalent
13197                    if (DEBUG_FILTERS) {
13198                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13199                                + " package: " + applicationInfo.packageName
13200                                + " activity: " + intent.activity.className
13201                                + " origPrio: " + intent.getPriority());
13202                    }
13203                    intent.setPriority(0);
13204                    return;
13205                }
13206            }
13207
13208            // find matching schemes subsets
13209            final Iterator<String> schemesIterator = intent.schemesIterator();
13210            if (schemesIterator != null) {
13211                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13212                        schemesIterator);
13213                if (intentListCopy.size() == 0) {
13214                    // no more intents to match; we're not equivalent
13215                    if (DEBUG_FILTERS) {
13216                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13217                                + " package: " + applicationInfo.packageName
13218                                + " activity: " + intent.activity.className
13219                                + " origPrio: " + intent.getPriority());
13220                    }
13221                    intent.setPriority(0);
13222                    return;
13223                }
13224            }
13225
13226            // find matching authorities subsets
13227            final Iterator<IntentFilter.AuthorityEntry>
13228                    authoritiesIterator = intent.authoritiesIterator();
13229            if (authoritiesIterator != null) {
13230                getIntentListSubset(intentListCopy,
13231                        new AuthoritiesIterGenerator(),
13232                        authoritiesIterator);
13233                if (intentListCopy.size() == 0) {
13234                    // no more intents to match; we're not equivalent
13235                    if (DEBUG_FILTERS) {
13236                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13237                                + " package: " + applicationInfo.packageName
13238                                + " activity: " + intent.activity.className
13239                                + " origPrio: " + intent.getPriority());
13240                    }
13241                    intent.setPriority(0);
13242                    return;
13243                }
13244            }
13245
13246            // we found matching filter(s); app gets the max priority of all intents
13247            int cappedPriority = 0;
13248            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13249                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13250            }
13251            if (intent.getPriority() > cappedPriority) {
13252                if (DEBUG_FILTERS) {
13253                    Slog.i(TAG, "Found matching filter(s);"
13254                            + " cap priority to " + cappedPriority + ";"
13255                            + " package: " + applicationInfo.packageName
13256                            + " activity: " + intent.activity.className
13257                            + " origPrio: " + intent.getPriority());
13258                }
13259                intent.setPriority(cappedPriority);
13260                return;
13261            }
13262            // all this for nothing; the requested priority was <= what was on the system
13263        }
13264
13265        public final void addActivity(PackageParser.Activity a, String type) {
13266            mActivities.put(a.getComponentName(), a);
13267            if (DEBUG_SHOW_INFO)
13268                Log.v(
13269                TAG, "  " + type + " " +
13270                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13271            if (DEBUG_SHOW_INFO)
13272                Log.v(TAG, "    Class=" + a.info.name);
13273            final int NI = a.intents.size();
13274            for (int j=0; j<NI; j++) {
13275                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13276                if ("activity".equals(type)) {
13277                    final PackageSetting ps =
13278                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13279                    final List<PackageParser.Activity> systemActivities =
13280                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13281                    adjustPriority(systemActivities, intent);
13282                }
13283                if (DEBUG_SHOW_INFO) {
13284                    Log.v(TAG, "    IntentFilter:");
13285                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13286                }
13287                if (!intent.debugCheck()) {
13288                    Log.w(TAG, "==> For Activity " + a.info.name);
13289                }
13290                addFilter(intent);
13291            }
13292        }
13293
13294        public final void removeActivity(PackageParser.Activity a, String type) {
13295            mActivities.remove(a.getComponentName());
13296            if (DEBUG_SHOW_INFO) {
13297                Log.v(TAG, "  " + type + " "
13298                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13299                                : a.info.name) + ":");
13300                Log.v(TAG, "    Class=" + a.info.name);
13301            }
13302            final int NI = a.intents.size();
13303            for (int j=0; j<NI; j++) {
13304                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13305                if (DEBUG_SHOW_INFO) {
13306                    Log.v(TAG, "    IntentFilter:");
13307                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13308                }
13309                removeFilter(intent);
13310            }
13311        }
13312
13313        @Override
13314        protected boolean allowFilterResult(
13315                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13316            ActivityInfo filterAi = filter.activity.info;
13317            for (int i=dest.size()-1; i>=0; i--) {
13318                ActivityInfo destAi = dest.get(i).activityInfo;
13319                if (destAi.name == filterAi.name
13320                        && destAi.packageName == filterAi.packageName) {
13321                    return false;
13322                }
13323            }
13324            return true;
13325        }
13326
13327        @Override
13328        protected ActivityIntentInfo[] newArray(int size) {
13329            return new ActivityIntentInfo[size];
13330        }
13331
13332        @Override
13333        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13334            if (!sUserManager.exists(userId)) return true;
13335            PackageParser.Package p = filter.activity.owner;
13336            if (p != null) {
13337                PackageSetting ps = (PackageSetting)p.mExtras;
13338                if (ps != null) {
13339                    // System apps are never considered stopped for purposes of
13340                    // filtering, because there may be no way for the user to
13341                    // actually re-launch them.
13342                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13343                            && ps.getStopped(userId);
13344                }
13345            }
13346            return false;
13347        }
13348
13349        @Override
13350        protected boolean isPackageForFilter(String packageName,
13351                PackageParser.ActivityIntentInfo info) {
13352            return packageName.equals(info.activity.owner.packageName);
13353        }
13354
13355        @Override
13356        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13357                int match, int userId) {
13358            if (!sUserManager.exists(userId)) return null;
13359            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13360                return null;
13361            }
13362            final PackageParser.Activity activity = info.activity;
13363            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13364            if (ps == null) {
13365                return null;
13366            }
13367            final PackageUserState userState = ps.readUserState(userId);
13368            ActivityInfo ai =
13369                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13370            if (ai == null) {
13371                return null;
13372            }
13373            final boolean matchExplicitlyVisibleOnly =
13374                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13375            final boolean matchVisibleToInstantApp =
13376                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13377            final boolean componentVisible =
13378                    matchVisibleToInstantApp
13379                    && info.isVisibleToInstantApp()
13380                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13381            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13382            // throw out filters that aren't visible to ephemeral apps
13383            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13384                return null;
13385            }
13386            // throw out instant app filters if we're not explicitly requesting them
13387            if (!matchInstantApp && userState.instantApp) {
13388                return null;
13389            }
13390            // throw out instant app filters if updates are available; will trigger
13391            // instant app resolution
13392            if (userState.instantApp && ps.isUpdateAvailable()) {
13393                return null;
13394            }
13395            final ResolveInfo res = new ResolveInfo();
13396            res.activityInfo = ai;
13397            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13398                res.filter = info;
13399            }
13400            if (info != null) {
13401                res.handleAllWebDataURI = info.handleAllWebDataURI();
13402            }
13403            res.priority = info.getPriority();
13404            res.preferredOrder = activity.owner.mPreferredOrder;
13405            //System.out.println("Result: " + res.activityInfo.className +
13406            //                   " = " + res.priority);
13407            res.match = match;
13408            res.isDefault = info.hasDefault;
13409            res.labelRes = info.labelRes;
13410            res.nonLocalizedLabel = info.nonLocalizedLabel;
13411            if (userNeedsBadging(userId)) {
13412                res.noResourceId = true;
13413            } else {
13414                res.icon = info.icon;
13415            }
13416            res.iconResourceId = info.icon;
13417            res.system = res.activityInfo.applicationInfo.isSystemApp();
13418            res.isInstantAppAvailable = userState.instantApp;
13419            return res;
13420        }
13421
13422        @Override
13423        protected void sortResults(List<ResolveInfo> results) {
13424            Collections.sort(results, mResolvePrioritySorter);
13425        }
13426
13427        @Override
13428        protected void dumpFilter(PrintWriter out, String prefix,
13429                PackageParser.ActivityIntentInfo filter) {
13430            out.print(prefix); out.print(
13431                    Integer.toHexString(System.identityHashCode(filter.activity)));
13432                    out.print(' ');
13433                    filter.activity.printComponentShortName(out);
13434                    out.print(" filter ");
13435                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13436        }
13437
13438        @Override
13439        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13440            return filter.activity;
13441        }
13442
13443        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13444            PackageParser.Activity activity = (PackageParser.Activity)label;
13445            out.print(prefix); out.print(
13446                    Integer.toHexString(System.identityHashCode(activity)));
13447                    out.print(' ');
13448                    activity.printComponentShortName(out);
13449            if (count > 1) {
13450                out.print(" ("); out.print(count); out.print(" filters)");
13451            }
13452            out.println();
13453        }
13454
13455        // Keys are String (activity class name), values are Activity.
13456        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13457                = new ArrayMap<ComponentName, PackageParser.Activity>();
13458        private int mFlags;
13459    }
13460
13461    private final class ServiceIntentResolver
13462            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13463        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13464                boolean defaultOnly, int userId) {
13465            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13466            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13467        }
13468
13469        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13470                int userId) {
13471            if (!sUserManager.exists(userId)) return null;
13472            mFlags = flags;
13473            return super.queryIntent(intent, resolvedType,
13474                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13475                    userId);
13476        }
13477
13478        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13479                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13480            if (!sUserManager.exists(userId)) return null;
13481            if (packageServices == null) {
13482                return null;
13483            }
13484            mFlags = flags;
13485            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13486            final int N = packageServices.size();
13487            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13488                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13489
13490            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13491            for (int i = 0; i < N; ++i) {
13492                intentFilters = packageServices.get(i).intents;
13493                if (intentFilters != null && intentFilters.size() > 0) {
13494                    PackageParser.ServiceIntentInfo[] array =
13495                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13496                    intentFilters.toArray(array);
13497                    listCut.add(array);
13498                }
13499            }
13500            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13501        }
13502
13503        public final void addService(PackageParser.Service s) {
13504            mServices.put(s.getComponentName(), s);
13505            if (DEBUG_SHOW_INFO) {
13506                Log.v(TAG, "  "
13507                        + (s.info.nonLocalizedLabel != null
13508                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13509                Log.v(TAG, "    Class=" + s.info.name);
13510            }
13511            final int NI = s.intents.size();
13512            int j;
13513            for (j=0; j<NI; j++) {
13514                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13515                if (DEBUG_SHOW_INFO) {
13516                    Log.v(TAG, "    IntentFilter:");
13517                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13518                }
13519                if (!intent.debugCheck()) {
13520                    Log.w(TAG, "==> For Service " + s.info.name);
13521                }
13522                addFilter(intent);
13523            }
13524        }
13525
13526        public final void removeService(PackageParser.Service s) {
13527            mServices.remove(s.getComponentName());
13528            if (DEBUG_SHOW_INFO) {
13529                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13530                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13531                Log.v(TAG, "    Class=" + s.info.name);
13532            }
13533            final int NI = s.intents.size();
13534            int j;
13535            for (j=0; j<NI; j++) {
13536                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13537                if (DEBUG_SHOW_INFO) {
13538                    Log.v(TAG, "    IntentFilter:");
13539                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13540                }
13541                removeFilter(intent);
13542            }
13543        }
13544
13545        @Override
13546        protected boolean allowFilterResult(
13547                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13548            ServiceInfo filterSi = filter.service.info;
13549            for (int i=dest.size()-1; i>=0; i--) {
13550                ServiceInfo destAi = dest.get(i).serviceInfo;
13551                if (destAi.name == filterSi.name
13552                        && destAi.packageName == filterSi.packageName) {
13553                    return false;
13554                }
13555            }
13556            return true;
13557        }
13558
13559        @Override
13560        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13561            return new PackageParser.ServiceIntentInfo[size];
13562        }
13563
13564        @Override
13565        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13566            if (!sUserManager.exists(userId)) return true;
13567            PackageParser.Package p = filter.service.owner;
13568            if (p != null) {
13569                PackageSetting ps = (PackageSetting)p.mExtras;
13570                if (ps != null) {
13571                    // System apps are never considered stopped for purposes of
13572                    // filtering, because there may be no way for the user to
13573                    // actually re-launch them.
13574                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13575                            && ps.getStopped(userId);
13576                }
13577            }
13578            return false;
13579        }
13580
13581        @Override
13582        protected boolean isPackageForFilter(String packageName,
13583                PackageParser.ServiceIntentInfo info) {
13584            return packageName.equals(info.service.owner.packageName);
13585        }
13586
13587        @Override
13588        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13589                int match, int userId) {
13590            if (!sUserManager.exists(userId)) return null;
13591            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13592            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13593                return null;
13594            }
13595            final PackageParser.Service service = info.service;
13596            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13597            if (ps == null) {
13598                return null;
13599            }
13600            final PackageUserState userState = ps.readUserState(userId);
13601            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13602                    userState, userId);
13603            if (si == null) {
13604                return null;
13605            }
13606            final boolean matchVisibleToInstantApp =
13607                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13608            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13609            // throw out filters that aren't visible to ephemeral apps
13610            if (matchVisibleToInstantApp
13611                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13612                return null;
13613            }
13614            // throw out ephemeral filters if we're not explicitly requesting them
13615            if (!isInstantApp && userState.instantApp) {
13616                return null;
13617            }
13618            // throw out instant app filters if updates are available; will trigger
13619            // instant app resolution
13620            if (userState.instantApp && ps.isUpdateAvailable()) {
13621                return null;
13622            }
13623            final ResolveInfo res = new ResolveInfo();
13624            res.serviceInfo = si;
13625            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13626                res.filter = filter;
13627            }
13628            res.priority = info.getPriority();
13629            res.preferredOrder = service.owner.mPreferredOrder;
13630            res.match = match;
13631            res.isDefault = info.hasDefault;
13632            res.labelRes = info.labelRes;
13633            res.nonLocalizedLabel = info.nonLocalizedLabel;
13634            res.icon = info.icon;
13635            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13636            return res;
13637        }
13638
13639        @Override
13640        protected void sortResults(List<ResolveInfo> results) {
13641            Collections.sort(results, mResolvePrioritySorter);
13642        }
13643
13644        @Override
13645        protected void dumpFilter(PrintWriter out, String prefix,
13646                PackageParser.ServiceIntentInfo filter) {
13647            out.print(prefix); out.print(
13648                    Integer.toHexString(System.identityHashCode(filter.service)));
13649                    out.print(' ');
13650                    filter.service.printComponentShortName(out);
13651                    out.print(" filter ");
13652                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13653        }
13654
13655        @Override
13656        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13657            return filter.service;
13658        }
13659
13660        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13661            PackageParser.Service service = (PackageParser.Service)label;
13662            out.print(prefix); out.print(
13663                    Integer.toHexString(System.identityHashCode(service)));
13664                    out.print(' ');
13665                    service.printComponentShortName(out);
13666            if (count > 1) {
13667                out.print(" ("); out.print(count); out.print(" filters)");
13668            }
13669            out.println();
13670        }
13671
13672//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13673//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13674//            final List<ResolveInfo> retList = Lists.newArrayList();
13675//            while (i.hasNext()) {
13676//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13677//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13678//                    retList.add(resolveInfo);
13679//                }
13680//            }
13681//            return retList;
13682//        }
13683
13684        // Keys are String (activity class name), values are Activity.
13685        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13686                = new ArrayMap<ComponentName, PackageParser.Service>();
13687        private int mFlags;
13688    }
13689
13690    private final class ProviderIntentResolver
13691            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13692        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13693                boolean defaultOnly, int userId) {
13694            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13695            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13696        }
13697
13698        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13699                int userId) {
13700            if (!sUserManager.exists(userId))
13701                return null;
13702            mFlags = flags;
13703            return super.queryIntent(intent, resolvedType,
13704                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13705                    userId);
13706        }
13707
13708        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13709                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13710            if (!sUserManager.exists(userId))
13711                return null;
13712            if (packageProviders == null) {
13713                return null;
13714            }
13715            mFlags = flags;
13716            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13717            final int N = packageProviders.size();
13718            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13719                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13720
13721            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13722            for (int i = 0; i < N; ++i) {
13723                intentFilters = packageProviders.get(i).intents;
13724                if (intentFilters != null && intentFilters.size() > 0) {
13725                    PackageParser.ProviderIntentInfo[] array =
13726                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13727                    intentFilters.toArray(array);
13728                    listCut.add(array);
13729                }
13730            }
13731            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13732        }
13733
13734        public final void addProvider(PackageParser.Provider p) {
13735            if (mProviders.containsKey(p.getComponentName())) {
13736                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13737                return;
13738            }
13739
13740            mProviders.put(p.getComponentName(), p);
13741            if (DEBUG_SHOW_INFO) {
13742                Log.v(TAG, "  "
13743                        + (p.info.nonLocalizedLabel != null
13744                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13745                Log.v(TAG, "    Class=" + p.info.name);
13746            }
13747            final int NI = p.intents.size();
13748            int j;
13749            for (j = 0; j < NI; j++) {
13750                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13751                if (DEBUG_SHOW_INFO) {
13752                    Log.v(TAG, "    IntentFilter:");
13753                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13754                }
13755                if (!intent.debugCheck()) {
13756                    Log.w(TAG, "==> For Provider " + p.info.name);
13757                }
13758                addFilter(intent);
13759            }
13760        }
13761
13762        public final void removeProvider(PackageParser.Provider p) {
13763            mProviders.remove(p.getComponentName());
13764            if (DEBUG_SHOW_INFO) {
13765                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13766                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13767                Log.v(TAG, "    Class=" + p.info.name);
13768            }
13769            final int NI = p.intents.size();
13770            int j;
13771            for (j = 0; j < NI; j++) {
13772                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13773                if (DEBUG_SHOW_INFO) {
13774                    Log.v(TAG, "    IntentFilter:");
13775                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13776                }
13777                removeFilter(intent);
13778            }
13779        }
13780
13781        @Override
13782        protected boolean allowFilterResult(
13783                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13784            ProviderInfo filterPi = filter.provider.info;
13785            for (int i = dest.size() - 1; i >= 0; i--) {
13786                ProviderInfo destPi = dest.get(i).providerInfo;
13787                if (destPi.name == filterPi.name
13788                        && destPi.packageName == filterPi.packageName) {
13789                    return false;
13790                }
13791            }
13792            return true;
13793        }
13794
13795        @Override
13796        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13797            return new PackageParser.ProviderIntentInfo[size];
13798        }
13799
13800        @Override
13801        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13802            if (!sUserManager.exists(userId))
13803                return true;
13804            PackageParser.Package p = filter.provider.owner;
13805            if (p != null) {
13806                PackageSetting ps = (PackageSetting) p.mExtras;
13807                if (ps != null) {
13808                    // System apps are never considered stopped for purposes of
13809                    // filtering, because there may be no way for the user to
13810                    // actually re-launch them.
13811                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13812                            && ps.getStopped(userId);
13813                }
13814            }
13815            return false;
13816        }
13817
13818        @Override
13819        protected boolean isPackageForFilter(String packageName,
13820                PackageParser.ProviderIntentInfo info) {
13821            return packageName.equals(info.provider.owner.packageName);
13822        }
13823
13824        @Override
13825        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13826                int match, int userId) {
13827            if (!sUserManager.exists(userId))
13828                return null;
13829            final PackageParser.ProviderIntentInfo info = filter;
13830            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13831                return null;
13832            }
13833            final PackageParser.Provider provider = info.provider;
13834            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13835            if (ps == null) {
13836                return null;
13837            }
13838            final PackageUserState userState = ps.readUserState(userId);
13839            final boolean matchVisibleToInstantApp =
13840                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13841            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13842            // throw out filters that aren't visible to instant applications
13843            if (matchVisibleToInstantApp
13844                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13845                return null;
13846            }
13847            // throw out instant application filters if we're not explicitly requesting them
13848            if (!isInstantApp && userState.instantApp) {
13849                return null;
13850            }
13851            // throw out instant application filters if updates are available; will trigger
13852            // instant application resolution
13853            if (userState.instantApp && ps.isUpdateAvailable()) {
13854                return null;
13855            }
13856            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13857                    userState, userId);
13858            if (pi == null) {
13859                return null;
13860            }
13861            final ResolveInfo res = new ResolveInfo();
13862            res.providerInfo = pi;
13863            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13864                res.filter = filter;
13865            }
13866            res.priority = info.getPriority();
13867            res.preferredOrder = provider.owner.mPreferredOrder;
13868            res.match = match;
13869            res.isDefault = info.hasDefault;
13870            res.labelRes = info.labelRes;
13871            res.nonLocalizedLabel = info.nonLocalizedLabel;
13872            res.icon = info.icon;
13873            res.system = res.providerInfo.applicationInfo.isSystemApp();
13874            return res;
13875        }
13876
13877        @Override
13878        protected void sortResults(List<ResolveInfo> results) {
13879            Collections.sort(results, mResolvePrioritySorter);
13880        }
13881
13882        @Override
13883        protected void dumpFilter(PrintWriter out, String prefix,
13884                PackageParser.ProviderIntentInfo filter) {
13885            out.print(prefix);
13886            out.print(
13887                    Integer.toHexString(System.identityHashCode(filter.provider)));
13888            out.print(' ');
13889            filter.provider.printComponentShortName(out);
13890            out.print(" filter ");
13891            out.println(Integer.toHexString(System.identityHashCode(filter)));
13892        }
13893
13894        @Override
13895        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13896            return filter.provider;
13897        }
13898
13899        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13900            PackageParser.Provider provider = (PackageParser.Provider)label;
13901            out.print(prefix); out.print(
13902                    Integer.toHexString(System.identityHashCode(provider)));
13903                    out.print(' ');
13904                    provider.printComponentShortName(out);
13905            if (count > 1) {
13906                out.print(" ("); out.print(count); out.print(" filters)");
13907            }
13908            out.println();
13909        }
13910
13911        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13912                = new ArrayMap<ComponentName, PackageParser.Provider>();
13913        private int mFlags;
13914    }
13915
13916    static final class EphemeralIntentResolver
13917            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13918        /**
13919         * The result that has the highest defined order. Ordering applies on a
13920         * per-package basis. Mapping is from package name to Pair of order and
13921         * EphemeralResolveInfo.
13922         * <p>
13923         * NOTE: This is implemented as a field variable for convenience and efficiency.
13924         * By having a field variable, we're able to track filter ordering as soon as
13925         * a non-zero order is defined. Otherwise, multiple loops across the result set
13926         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13927         * this needs to be contained entirely within {@link #filterResults}.
13928         */
13929        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13930
13931        @Override
13932        protected AuxiliaryResolveInfo[] newArray(int size) {
13933            return new AuxiliaryResolveInfo[size];
13934        }
13935
13936        @Override
13937        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13938            return true;
13939        }
13940
13941        @Override
13942        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13943                int userId) {
13944            if (!sUserManager.exists(userId)) {
13945                return null;
13946            }
13947            final String packageName = responseObj.resolveInfo.getPackageName();
13948            final Integer order = responseObj.getOrder();
13949            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13950                    mOrderResult.get(packageName);
13951            // ordering is enabled and this item's order isn't high enough
13952            if (lastOrderResult != null && lastOrderResult.first >= order) {
13953                return null;
13954            }
13955            final InstantAppResolveInfo res = responseObj.resolveInfo;
13956            if (order > 0) {
13957                // non-zero order, enable ordering
13958                mOrderResult.put(packageName, new Pair<>(order, res));
13959            }
13960            return responseObj;
13961        }
13962
13963        @Override
13964        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13965            // only do work if ordering is enabled [most of the time it won't be]
13966            if (mOrderResult.size() == 0) {
13967                return;
13968            }
13969            int resultSize = results.size();
13970            for (int i = 0; i < resultSize; i++) {
13971                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13972                final String packageName = info.getPackageName();
13973                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13974                if (savedInfo == null) {
13975                    // package doesn't having ordering
13976                    continue;
13977                }
13978                if (savedInfo.second == info) {
13979                    // circled back to the highest ordered item; remove from order list
13980                    mOrderResult.remove(savedInfo);
13981                    if (mOrderResult.size() == 0) {
13982                        // no more ordered items
13983                        break;
13984                    }
13985                    continue;
13986                }
13987                // item has a worse order, remove it from the result list
13988                results.remove(i);
13989                resultSize--;
13990                i--;
13991            }
13992        }
13993    }
13994
13995    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13996            new Comparator<ResolveInfo>() {
13997        public int compare(ResolveInfo r1, ResolveInfo r2) {
13998            int v1 = r1.priority;
13999            int v2 = r2.priority;
14000            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14001            if (v1 != v2) {
14002                return (v1 > v2) ? -1 : 1;
14003            }
14004            v1 = r1.preferredOrder;
14005            v2 = r2.preferredOrder;
14006            if (v1 != v2) {
14007                return (v1 > v2) ? -1 : 1;
14008            }
14009            if (r1.isDefault != r2.isDefault) {
14010                return r1.isDefault ? -1 : 1;
14011            }
14012            v1 = r1.match;
14013            v2 = r2.match;
14014            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14015            if (v1 != v2) {
14016                return (v1 > v2) ? -1 : 1;
14017            }
14018            if (r1.system != r2.system) {
14019                return r1.system ? -1 : 1;
14020            }
14021            if (r1.activityInfo != null) {
14022                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14023            }
14024            if (r1.serviceInfo != null) {
14025                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14026            }
14027            if (r1.providerInfo != null) {
14028                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14029            }
14030            return 0;
14031        }
14032    };
14033
14034    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14035            new Comparator<ProviderInfo>() {
14036        public int compare(ProviderInfo p1, ProviderInfo p2) {
14037            final int v1 = p1.initOrder;
14038            final int v2 = p2.initOrder;
14039            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14040        }
14041    };
14042
14043    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14044            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14045            final int[] userIds) {
14046        mHandler.post(new Runnable() {
14047            @Override
14048            public void run() {
14049                try {
14050                    final IActivityManager am = ActivityManager.getService();
14051                    if (am == null) return;
14052                    final int[] resolvedUserIds;
14053                    if (userIds == null) {
14054                        resolvedUserIds = am.getRunningUserIds();
14055                    } else {
14056                        resolvedUserIds = userIds;
14057                    }
14058                    for (int id : resolvedUserIds) {
14059                        final Intent intent = new Intent(action,
14060                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14061                        if (extras != null) {
14062                            intent.putExtras(extras);
14063                        }
14064                        if (targetPkg != null) {
14065                            intent.setPackage(targetPkg);
14066                        }
14067                        // Modify the UID when posting to other users
14068                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14069                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14070                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14071                            intent.putExtra(Intent.EXTRA_UID, uid);
14072                        }
14073                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14074                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14075                        if (DEBUG_BROADCASTS) {
14076                            RuntimeException here = new RuntimeException("here");
14077                            here.fillInStackTrace();
14078                            Slog.d(TAG, "Sending to user " + id + ": "
14079                                    + intent.toShortString(false, true, false, false)
14080                                    + " " + intent.getExtras(), here);
14081                        }
14082                        am.broadcastIntent(null, intent, null, finishedReceiver,
14083                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14084                                null, finishedReceiver != null, false, id);
14085                    }
14086                } catch (RemoteException ex) {
14087                }
14088            }
14089        });
14090    }
14091
14092    /**
14093     * Check if the external storage media is available. This is true if there
14094     * is a mounted external storage medium or if the external storage is
14095     * emulated.
14096     */
14097    private boolean isExternalMediaAvailable() {
14098        return mMediaMounted || Environment.isExternalStorageEmulated();
14099    }
14100
14101    @Override
14102    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14103        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14104            return null;
14105        }
14106        // writer
14107        synchronized (mPackages) {
14108            if (!isExternalMediaAvailable()) {
14109                // If the external storage is no longer mounted at this point,
14110                // the caller may not have been able to delete all of this
14111                // packages files and can not delete any more.  Bail.
14112                return null;
14113            }
14114            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14115            if (lastPackage != null) {
14116                pkgs.remove(lastPackage);
14117            }
14118            if (pkgs.size() > 0) {
14119                return pkgs.get(0);
14120            }
14121        }
14122        return null;
14123    }
14124
14125    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14126        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14127                userId, andCode ? 1 : 0, packageName);
14128        if (mSystemReady) {
14129            msg.sendToTarget();
14130        } else {
14131            if (mPostSystemReadyMessages == null) {
14132                mPostSystemReadyMessages = new ArrayList<>();
14133            }
14134            mPostSystemReadyMessages.add(msg);
14135        }
14136    }
14137
14138    void startCleaningPackages() {
14139        // reader
14140        if (!isExternalMediaAvailable()) {
14141            return;
14142        }
14143        synchronized (mPackages) {
14144            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14145                return;
14146            }
14147        }
14148        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14149        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14150        IActivityManager am = ActivityManager.getService();
14151        if (am != null) {
14152            int dcsUid = -1;
14153            synchronized (mPackages) {
14154                if (!mDefaultContainerWhitelisted) {
14155                    mDefaultContainerWhitelisted = true;
14156                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14157                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14158                }
14159            }
14160            try {
14161                if (dcsUid > 0) {
14162                    am.backgroundWhitelistUid(dcsUid);
14163                }
14164                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14165                        UserHandle.USER_SYSTEM);
14166            } catch (RemoteException e) {
14167            }
14168        }
14169    }
14170
14171    @Override
14172    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14173            int installFlags, String installerPackageName, int userId) {
14174        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14175
14176        final int callingUid = Binder.getCallingUid();
14177        enforceCrossUserPermission(callingUid, userId,
14178                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14179
14180        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14181            try {
14182                if (observer != null) {
14183                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14184                }
14185            } catch (RemoteException re) {
14186            }
14187            return;
14188        }
14189
14190        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14191            installFlags |= PackageManager.INSTALL_FROM_ADB;
14192
14193        } else {
14194            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14195            // about installerPackageName.
14196
14197            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14198            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14199        }
14200
14201        UserHandle user;
14202        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14203            user = UserHandle.ALL;
14204        } else {
14205            user = new UserHandle(userId);
14206        }
14207
14208        // Only system components can circumvent runtime permissions when installing.
14209        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14210                && mContext.checkCallingOrSelfPermission(Manifest.permission
14211                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14212            throw new SecurityException("You need the "
14213                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14214                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14215        }
14216
14217        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14218                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14219            throw new IllegalArgumentException(
14220                    "New installs into ASEC containers no longer supported");
14221        }
14222
14223        final File originFile = new File(originPath);
14224        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14225
14226        final Message msg = mHandler.obtainMessage(INIT_COPY);
14227        final VerificationInfo verificationInfo = new VerificationInfo(
14228                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14229        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14230                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14231                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14232                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14233        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14234        msg.obj = params;
14235
14236        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14237                System.identityHashCode(msg.obj));
14238        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14239                System.identityHashCode(msg.obj));
14240
14241        mHandler.sendMessage(msg);
14242    }
14243
14244
14245    /**
14246     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14247     * it is acting on behalf on an enterprise or the user).
14248     *
14249     * Note that the ordering of the conditionals in this method is important. The checks we perform
14250     * are as follows, in this order:
14251     *
14252     * 1) If the install is being performed by a system app, we can trust the app to have set the
14253     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14254     *    what it is.
14255     * 2) If the install is being performed by a device or profile owner app, the install reason
14256     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14257     *    set the install reason correctly. If the app targets an older SDK version where install
14258     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14259     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14260     * 3) In all other cases, the install is being performed by a regular app that is neither part
14261     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14262     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14263     *    set to enterprise policy and if so, change it to unknown instead.
14264     */
14265    private int fixUpInstallReason(String installerPackageName, int installerUid,
14266            int installReason) {
14267        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14268                == PERMISSION_GRANTED) {
14269            // If the install is being performed by a system app, we trust that app to have set the
14270            // install reason correctly.
14271            return installReason;
14272        }
14273
14274        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14275            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14276        if (dpm != null) {
14277            ComponentName owner = null;
14278            try {
14279                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14280                if (owner == null) {
14281                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14282                }
14283            } catch (RemoteException e) {
14284            }
14285            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14286                // If the install is being performed by a device or profile owner, the install
14287                // reason should be enterprise policy.
14288                return PackageManager.INSTALL_REASON_POLICY;
14289            }
14290        }
14291
14292        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14293            // If the install is being performed by a regular app (i.e. neither system app nor
14294            // device or profile owner), we have no reason to believe that the app is acting on
14295            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14296            // change it to unknown instead.
14297            return PackageManager.INSTALL_REASON_UNKNOWN;
14298        }
14299
14300        // If the install is being performed by a regular app and the install reason was set to any
14301        // value but enterprise policy, leave the install reason unchanged.
14302        return installReason;
14303    }
14304
14305    void installStage(String packageName, File stagedDir, String stagedCid,
14306            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14307            String installerPackageName, int installerUid, UserHandle user,
14308            Certificate[][] certificates) {
14309        if (DEBUG_EPHEMERAL) {
14310            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14311                Slog.d(TAG, "Ephemeral install of " + packageName);
14312            }
14313        }
14314        final VerificationInfo verificationInfo = new VerificationInfo(
14315                sessionParams.originatingUri, sessionParams.referrerUri,
14316                sessionParams.originatingUid, installerUid);
14317
14318        final OriginInfo origin;
14319        if (stagedDir != null) {
14320            origin = OriginInfo.fromStagedFile(stagedDir);
14321        } else {
14322            origin = OriginInfo.fromStagedContainer(stagedCid);
14323        }
14324
14325        final Message msg = mHandler.obtainMessage(INIT_COPY);
14326        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14327                sessionParams.installReason);
14328        final InstallParams params = new InstallParams(origin, null, observer,
14329                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14330                verificationInfo, user, sessionParams.abiOverride,
14331                sessionParams.grantedRuntimePermissions, certificates, installReason);
14332        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14333        msg.obj = params;
14334
14335        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14336                System.identityHashCode(msg.obj));
14337        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14338                System.identityHashCode(msg.obj));
14339
14340        mHandler.sendMessage(msg);
14341    }
14342
14343    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14344            int userId) {
14345        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14346        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
14347
14348        // Send a session commit broadcast
14349        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14350        info.installReason = pkgSetting.getInstallReason(userId);
14351        info.appPackageName = packageName;
14352        sendSessionCommitBroadcast(info, userId);
14353    }
14354
14355    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
14356        if (ArrayUtils.isEmpty(userIds)) {
14357            return;
14358        }
14359        Bundle extras = new Bundle(1);
14360        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14361        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14362
14363        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14364                packageName, extras, 0, null, null, userIds);
14365        if (isSystem) {
14366            mHandler.post(() -> {
14367                        for (int userId : userIds) {
14368                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
14369                        }
14370                    }
14371            );
14372        }
14373    }
14374
14375    /**
14376     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14377     * automatically without needing an explicit launch.
14378     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14379     */
14380    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
14381        // If user is not running, the app didn't miss any broadcast
14382        if (!mUserManagerInternal.isUserRunning(userId)) {
14383            return;
14384        }
14385        final IActivityManager am = ActivityManager.getService();
14386        try {
14387            // Deliver LOCKED_BOOT_COMPLETED first
14388            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14389                    .setPackage(packageName);
14390            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14391            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14392                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14393
14394            // Deliver BOOT_COMPLETED only if user is unlocked
14395            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14396                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14397                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14398                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14399            }
14400        } catch (RemoteException e) {
14401            throw e.rethrowFromSystemServer();
14402        }
14403    }
14404
14405    @Override
14406    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14407            int userId) {
14408        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14409        PackageSetting pkgSetting;
14410        final int callingUid = Binder.getCallingUid();
14411        enforceCrossUserPermission(callingUid, userId,
14412                true /* requireFullPermission */, true /* checkShell */,
14413                "setApplicationHiddenSetting for user " + userId);
14414
14415        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14416            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14417            return false;
14418        }
14419
14420        long callingId = Binder.clearCallingIdentity();
14421        try {
14422            boolean sendAdded = false;
14423            boolean sendRemoved = false;
14424            // writer
14425            synchronized (mPackages) {
14426                pkgSetting = mSettings.mPackages.get(packageName);
14427                if (pkgSetting == null) {
14428                    return false;
14429                }
14430                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14431                    return false;
14432                }
14433                // Do not allow "android" is being disabled
14434                if ("android".equals(packageName)) {
14435                    Slog.w(TAG, "Cannot hide package: android");
14436                    return false;
14437                }
14438                // Cannot hide static shared libs as they are considered
14439                // a part of the using app (emulating static linking). Also
14440                // static libs are installed always on internal storage.
14441                PackageParser.Package pkg = mPackages.get(packageName);
14442                if (pkg != null && pkg.staticSharedLibName != null) {
14443                    Slog.w(TAG, "Cannot hide package: " + packageName
14444                            + " providing static shared library: "
14445                            + pkg.staticSharedLibName);
14446                    return false;
14447                }
14448                // Only allow protected packages to hide themselves.
14449                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14450                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14451                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14452                    return false;
14453                }
14454
14455                if (pkgSetting.getHidden(userId) != hidden) {
14456                    pkgSetting.setHidden(hidden, userId);
14457                    mSettings.writePackageRestrictionsLPr(userId);
14458                    if (hidden) {
14459                        sendRemoved = true;
14460                    } else {
14461                        sendAdded = true;
14462                    }
14463                }
14464            }
14465            if (sendAdded) {
14466                sendPackageAddedForUser(packageName, pkgSetting, userId);
14467                return true;
14468            }
14469            if (sendRemoved) {
14470                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14471                        "hiding pkg");
14472                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14473                return true;
14474            }
14475        } finally {
14476            Binder.restoreCallingIdentity(callingId);
14477        }
14478        return false;
14479    }
14480
14481    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14482            int userId) {
14483        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14484        info.removedPackage = packageName;
14485        info.installerPackageName = pkgSetting.installerPackageName;
14486        info.removedUsers = new int[] {userId};
14487        info.broadcastUsers = new int[] {userId};
14488        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14489        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14490    }
14491
14492    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14493        if (pkgList.length > 0) {
14494            Bundle extras = new Bundle(1);
14495            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14496
14497            sendPackageBroadcast(
14498                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14499                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14500                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14501                    new int[] {userId});
14502        }
14503    }
14504
14505    /**
14506     * Returns true if application is not found or there was an error. Otherwise it returns
14507     * the hidden state of the package for the given user.
14508     */
14509    @Override
14510    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14511        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14512        final int callingUid = Binder.getCallingUid();
14513        enforceCrossUserPermission(callingUid, userId,
14514                true /* requireFullPermission */, false /* checkShell */,
14515                "getApplicationHidden for user " + userId);
14516        PackageSetting ps;
14517        long callingId = Binder.clearCallingIdentity();
14518        try {
14519            // writer
14520            synchronized (mPackages) {
14521                ps = mSettings.mPackages.get(packageName);
14522                if (ps == null) {
14523                    return true;
14524                }
14525                if (filterAppAccessLPr(ps, callingUid, userId)) {
14526                    return true;
14527                }
14528                return ps.getHidden(userId);
14529            }
14530        } finally {
14531            Binder.restoreCallingIdentity(callingId);
14532        }
14533    }
14534
14535    /**
14536     * @hide
14537     */
14538    @Override
14539    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14540            int installReason) {
14541        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14542                null);
14543        PackageSetting pkgSetting;
14544        final int callingUid = Binder.getCallingUid();
14545        enforceCrossUserPermission(callingUid, userId,
14546                true /* requireFullPermission */, true /* checkShell */,
14547                "installExistingPackage for user " + userId);
14548        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14549            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14550        }
14551
14552        long callingId = Binder.clearCallingIdentity();
14553        try {
14554            boolean installed = false;
14555            final boolean instantApp =
14556                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14557            final boolean fullApp =
14558                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14559
14560            // writer
14561            synchronized (mPackages) {
14562                pkgSetting = mSettings.mPackages.get(packageName);
14563                if (pkgSetting == null) {
14564                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14565                }
14566                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14567                    // only allow the existing package to be used if it's installed as a full
14568                    // application for at least one user
14569                    boolean installAllowed = false;
14570                    for (int checkUserId : sUserManager.getUserIds()) {
14571                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14572                        if (installAllowed) {
14573                            break;
14574                        }
14575                    }
14576                    if (!installAllowed) {
14577                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14578                    }
14579                }
14580                if (!pkgSetting.getInstalled(userId)) {
14581                    pkgSetting.setInstalled(true, userId);
14582                    pkgSetting.setHidden(false, userId);
14583                    pkgSetting.setInstallReason(installReason, userId);
14584                    mSettings.writePackageRestrictionsLPr(userId);
14585                    mSettings.writeKernelMappingLPr(pkgSetting);
14586                    installed = true;
14587                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14588                    // upgrade app from instant to full; we don't allow app downgrade
14589                    installed = true;
14590                }
14591                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14592            }
14593
14594            if (installed) {
14595                if (pkgSetting.pkg != null) {
14596                    synchronized (mInstallLock) {
14597                        // We don't need to freeze for a brand new install
14598                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14599                    }
14600                }
14601                sendPackageAddedForUser(packageName, pkgSetting, userId);
14602                synchronized (mPackages) {
14603                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14604                }
14605            }
14606        } finally {
14607            Binder.restoreCallingIdentity(callingId);
14608        }
14609
14610        return PackageManager.INSTALL_SUCCEEDED;
14611    }
14612
14613    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14614            boolean instantApp, boolean fullApp) {
14615        // no state specified; do nothing
14616        if (!instantApp && !fullApp) {
14617            return;
14618        }
14619        if (userId != UserHandle.USER_ALL) {
14620            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14621                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14622            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14623                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14624            }
14625        } else {
14626            for (int currentUserId : sUserManager.getUserIds()) {
14627                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14628                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14629                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14630                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14631                }
14632            }
14633        }
14634    }
14635
14636    boolean isUserRestricted(int userId, String restrictionKey) {
14637        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14638        if (restrictions.getBoolean(restrictionKey, false)) {
14639            Log.w(TAG, "User is restricted: " + restrictionKey);
14640            return true;
14641        }
14642        return false;
14643    }
14644
14645    @Override
14646    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14647            int userId) {
14648        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14649        final int callingUid = Binder.getCallingUid();
14650        enforceCrossUserPermission(callingUid, userId,
14651                true /* requireFullPermission */, true /* checkShell */,
14652                "setPackagesSuspended for user " + userId);
14653
14654        if (ArrayUtils.isEmpty(packageNames)) {
14655            return packageNames;
14656        }
14657
14658        // List of package names for whom the suspended state has changed.
14659        List<String> changedPackages = new ArrayList<>(packageNames.length);
14660        // List of package names for whom the suspended state is not set as requested in this
14661        // method.
14662        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14663        long callingId = Binder.clearCallingIdentity();
14664        try {
14665            for (int i = 0; i < packageNames.length; i++) {
14666                String packageName = packageNames[i];
14667                boolean changed = false;
14668                final int appId;
14669                synchronized (mPackages) {
14670                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14671                    if (pkgSetting == null
14672                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14673                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14674                                + "\". Skipping suspending/un-suspending.");
14675                        unactionedPackages.add(packageName);
14676                        continue;
14677                    }
14678                    appId = pkgSetting.appId;
14679                    if (pkgSetting.getSuspended(userId) != suspended) {
14680                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14681                            unactionedPackages.add(packageName);
14682                            continue;
14683                        }
14684                        pkgSetting.setSuspended(suspended, userId);
14685                        mSettings.writePackageRestrictionsLPr(userId);
14686                        changed = true;
14687                        changedPackages.add(packageName);
14688                    }
14689                }
14690
14691                if (changed && suspended) {
14692                    killApplication(packageName, UserHandle.getUid(userId, appId),
14693                            "suspending package");
14694                }
14695            }
14696        } finally {
14697            Binder.restoreCallingIdentity(callingId);
14698        }
14699
14700        if (!changedPackages.isEmpty()) {
14701            sendPackagesSuspendedForUser(changedPackages.toArray(
14702                    new String[changedPackages.size()]), userId, suspended);
14703        }
14704
14705        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14706    }
14707
14708    @Override
14709    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14710        final int callingUid = Binder.getCallingUid();
14711        enforceCrossUserPermission(callingUid, userId,
14712                true /* requireFullPermission */, false /* checkShell */,
14713                "isPackageSuspendedForUser for user " + userId);
14714        synchronized (mPackages) {
14715            final PackageSetting ps = mSettings.mPackages.get(packageName);
14716            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14717                throw new IllegalArgumentException("Unknown target package: " + packageName);
14718            }
14719            return ps.getSuspended(userId);
14720        }
14721    }
14722
14723    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14724        if (isPackageDeviceAdmin(packageName, userId)) {
14725            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14726                    + "\": has an active device admin");
14727            return false;
14728        }
14729
14730        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14731        if (packageName.equals(activeLauncherPackageName)) {
14732            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14733                    + "\": contains the active launcher");
14734            return false;
14735        }
14736
14737        if (packageName.equals(mRequiredInstallerPackage)) {
14738            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14739                    + "\": required for package installation");
14740            return false;
14741        }
14742
14743        if (packageName.equals(mRequiredUninstallerPackage)) {
14744            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14745                    + "\": required for package uninstallation");
14746            return false;
14747        }
14748
14749        if (packageName.equals(mRequiredVerifierPackage)) {
14750            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14751                    + "\": required for package verification");
14752            return false;
14753        }
14754
14755        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14756            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14757                    + "\": is the default dialer");
14758            return false;
14759        }
14760
14761        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14762            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14763                    + "\": protected package");
14764            return false;
14765        }
14766
14767        // Cannot suspend static shared libs as they are considered
14768        // a part of the using app (emulating static linking). Also
14769        // static libs are installed always on internal storage.
14770        PackageParser.Package pkg = mPackages.get(packageName);
14771        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14772            Slog.w(TAG, "Cannot suspend package: " + packageName
14773                    + " providing static shared library: "
14774                    + pkg.staticSharedLibName);
14775            return false;
14776        }
14777
14778        return true;
14779    }
14780
14781    private String getActiveLauncherPackageName(int userId) {
14782        Intent intent = new Intent(Intent.ACTION_MAIN);
14783        intent.addCategory(Intent.CATEGORY_HOME);
14784        ResolveInfo resolveInfo = resolveIntent(
14785                intent,
14786                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14787                PackageManager.MATCH_DEFAULT_ONLY,
14788                userId);
14789
14790        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14791    }
14792
14793    private String getDefaultDialerPackageName(int userId) {
14794        synchronized (mPackages) {
14795            return mSettings.getDefaultDialerPackageNameLPw(userId);
14796        }
14797    }
14798
14799    @Override
14800    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14801        mContext.enforceCallingOrSelfPermission(
14802                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14803                "Only package verification agents can verify applications");
14804
14805        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14806        final PackageVerificationResponse response = new PackageVerificationResponse(
14807                verificationCode, Binder.getCallingUid());
14808        msg.arg1 = id;
14809        msg.obj = response;
14810        mHandler.sendMessage(msg);
14811    }
14812
14813    @Override
14814    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14815            long millisecondsToDelay) {
14816        mContext.enforceCallingOrSelfPermission(
14817                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14818                "Only package verification agents can extend verification timeouts");
14819
14820        final PackageVerificationState state = mPendingVerification.get(id);
14821        final PackageVerificationResponse response = new PackageVerificationResponse(
14822                verificationCodeAtTimeout, Binder.getCallingUid());
14823
14824        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14825            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14826        }
14827        if (millisecondsToDelay < 0) {
14828            millisecondsToDelay = 0;
14829        }
14830        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14831                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14832            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14833        }
14834
14835        if ((state != null) && !state.timeoutExtended()) {
14836            state.extendTimeout();
14837
14838            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14839            msg.arg1 = id;
14840            msg.obj = response;
14841            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14842        }
14843    }
14844
14845    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14846            int verificationCode, UserHandle user) {
14847        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14848        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14849        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14850        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14851        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14852
14853        mContext.sendBroadcastAsUser(intent, user,
14854                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14855    }
14856
14857    private ComponentName matchComponentForVerifier(String packageName,
14858            List<ResolveInfo> receivers) {
14859        ActivityInfo targetReceiver = null;
14860
14861        final int NR = receivers.size();
14862        for (int i = 0; i < NR; i++) {
14863            final ResolveInfo info = receivers.get(i);
14864            if (info.activityInfo == null) {
14865                continue;
14866            }
14867
14868            if (packageName.equals(info.activityInfo.packageName)) {
14869                targetReceiver = info.activityInfo;
14870                break;
14871            }
14872        }
14873
14874        if (targetReceiver == null) {
14875            return null;
14876        }
14877
14878        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14879    }
14880
14881    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14882            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14883        if (pkgInfo.verifiers.length == 0) {
14884            return null;
14885        }
14886
14887        final int N = pkgInfo.verifiers.length;
14888        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14889        for (int i = 0; i < N; i++) {
14890            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14891
14892            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14893                    receivers);
14894            if (comp == null) {
14895                continue;
14896            }
14897
14898            final int verifierUid = getUidForVerifier(verifierInfo);
14899            if (verifierUid == -1) {
14900                continue;
14901            }
14902
14903            if (DEBUG_VERIFY) {
14904                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14905                        + " with the correct signature");
14906            }
14907            sufficientVerifiers.add(comp);
14908            verificationState.addSufficientVerifier(verifierUid);
14909        }
14910
14911        return sufficientVerifiers;
14912    }
14913
14914    private int getUidForVerifier(VerifierInfo verifierInfo) {
14915        synchronized (mPackages) {
14916            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14917            if (pkg == null) {
14918                return -1;
14919            } else if (pkg.mSignatures.length != 1) {
14920                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14921                        + " has more than one signature; ignoring");
14922                return -1;
14923            }
14924
14925            /*
14926             * If the public key of the package's signature does not match
14927             * our expected public key, then this is a different package and
14928             * we should skip.
14929             */
14930
14931            final byte[] expectedPublicKey;
14932            try {
14933                final Signature verifierSig = pkg.mSignatures[0];
14934                final PublicKey publicKey = verifierSig.getPublicKey();
14935                expectedPublicKey = publicKey.getEncoded();
14936            } catch (CertificateException e) {
14937                return -1;
14938            }
14939
14940            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14941
14942            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14943                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14944                        + " does not have the expected public key; ignoring");
14945                return -1;
14946            }
14947
14948            return pkg.applicationInfo.uid;
14949        }
14950    }
14951
14952    @Override
14953    public void finishPackageInstall(int token, boolean didLaunch) {
14954        enforceSystemOrRoot("Only the system is allowed to finish installs");
14955
14956        if (DEBUG_INSTALL) {
14957            Slog.v(TAG, "BM finishing package install for " + token);
14958        }
14959        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14960
14961        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14962        mHandler.sendMessage(msg);
14963    }
14964
14965    /**
14966     * Get the verification agent timeout.  Used for both the APK verifier and the
14967     * intent filter verifier.
14968     *
14969     * @return verification timeout in milliseconds
14970     */
14971    private long getVerificationTimeout() {
14972        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14973                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14974                DEFAULT_VERIFICATION_TIMEOUT);
14975    }
14976
14977    /**
14978     * Get the default verification agent response code.
14979     *
14980     * @return default verification response code
14981     */
14982    private int getDefaultVerificationResponse(UserHandle user) {
14983        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14984            return PackageManager.VERIFICATION_REJECT;
14985        }
14986        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14987                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14988                DEFAULT_VERIFICATION_RESPONSE);
14989    }
14990
14991    /**
14992     * Check whether or not package verification has been enabled.
14993     *
14994     * @return true if verification should be performed
14995     */
14996    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14997        if (!DEFAULT_VERIFY_ENABLE) {
14998            return false;
14999        }
15000
15001        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15002
15003        // Check if installing from ADB
15004        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15005            // Do not run verification in a test harness environment
15006            if (ActivityManager.isRunningInTestHarness()) {
15007                return false;
15008            }
15009            if (ensureVerifyAppsEnabled) {
15010                return true;
15011            }
15012            // Check if the developer does not want package verification for ADB installs
15013            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15014                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15015                return false;
15016            }
15017        } else {
15018            // only when not installed from ADB, skip verification for instant apps when
15019            // the installer and verifier are the same.
15020            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15021                if (mInstantAppInstallerActivity != null
15022                        && mInstantAppInstallerActivity.packageName.equals(
15023                                mRequiredVerifierPackage)) {
15024                    try {
15025                        mContext.getSystemService(AppOpsManager.class)
15026                                .checkPackage(installerUid, mRequiredVerifierPackage);
15027                        if (DEBUG_VERIFY) {
15028                            Slog.i(TAG, "disable verification for instant app");
15029                        }
15030                        return false;
15031                    } catch (SecurityException ignore) { }
15032                }
15033            }
15034        }
15035
15036        if (ensureVerifyAppsEnabled) {
15037            return true;
15038        }
15039
15040        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15041                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15042    }
15043
15044    @Override
15045    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15046            throws RemoteException {
15047        mContext.enforceCallingOrSelfPermission(
15048                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15049                "Only intentfilter verification agents can verify applications");
15050
15051        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15052        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15053                Binder.getCallingUid(), verificationCode, failedDomains);
15054        msg.arg1 = id;
15055        msg.obj = response;
15056        mHandler.sendMessage(msg);
15057    }
15058
15059    @Override
15060    public int getIntentVerificationStatus(String packageName, int userId) {
15061        final int callingUid = Binder.getCallingUid();
15062        if (getInstantAppPackageName(callingUid) != null) {
15063            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15064        }
15065        synchronized (mPackages) {
15066            final PackageSetting ps = mSettings.mPackages.get(packageName);
15067            if (ps == null
15068                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15069                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15070            }
15071            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15072        }
15073    }
15074
15075    @Override
15076    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15077        mContext.enforceCallingOrSelfPermission(
15078                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15079
15080        boolean result = false;
15081        synchronized (mPackages) {
15082            final PackageSetting ps = mSettings.mPackages.get(packageName);
15083            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15084                return false;
15085            }
15086            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15087        }
15088        if (result) {
15089            scheduleWritePackageRestrictionsLocked(userId);
15090        }
15091        return result;
15092    }
15093
15094    @Override
15095    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15096            String packageName) {
15097        final int callingUid = Binder.getCallingUid();
15098        if (getInstantAppPackageName(callingUid) != null) {
15099            return ParceledListSlice.emptyList();
15100        }
15101        synchronized (mPackages) {
15102            final PackageSetting ps = mSettings.mPackages.get(packageName);
15103            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15104                return ParceledListSlice.emptyList();
15105            }
15106            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15107        }
15108    }
15109
15110    @Override
15111    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15112        if (TextUtils.isEmpty(packageName)) {
15113            return ParceledListSlice.emptyList();
15114        }
15115        final int callingUid = Binder.getCallingUid();
15116        final int callingUserId = UserHandle.getUserId(callingUid);
15117        synchronized (mPackages) {
15118            PackageParser.Package pkg = mPackages.get(packageName);
15119            if (pkg == null || pkg.activities == null) {
15120                return ParceledListSlice.emptyList();
15121            }
15122            if (pkg.mExtras == null) {
15123                return ParceledListSlice.emptyList();
15124            }
15125            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15126            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15127                return ParceledListSlice.emptyList();
15128            }
15129            final int count = pkg.activities.size();
15130            ArrayList<IntentFilter> result = new ArrayList<>();
15131            for (int n=0; n<count; n++) {
15132                PackageParser.Activity activity = pkg.activities.get(n);
15133                if (activity.intents != null && activity.intents.size() > 0) {
15134                    result.addAll(activity.intents);
15135                }
15136            }
15137            return new ParceledListSlice<>(result);
15138        }
15139    }
15140
15141    @Override
15142    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15143        mContext.enforceCallingOrSelfPermission(
15144                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15145
15146        synchronized (mPackages) {
15147            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15148            if (packageName != null) {
15149                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15150                        packageName, userId);
15151            }
15152            return result;
15153        }
15154    }
15155
15156    @Override
15157    public String getDefaultBrowserPackageName(int userId) {
15158        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15159            return null;
15160        }
15161        synchronized (mPackages) {
15162            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15163        }
15164    }
15165
15166    /**
15167     * Get the "allow unknown sources" setting.
15168     *
15169     * @return the current "allow unknown sources" setting
15170     */
15171    private int getUnknownSourcesSettings() {
15172        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15173                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15174                -1);
15175    }
15176
15177    @Override
15178    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15179        final int callingUid = Binder.getCallingUid();
15180        if (getInstantAppPackageName(callingUid) != null) {
15181            return;
15182        }
15183        // writer
15184        synchronized (mPackages) {
15185            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15186            if (targetPackageSetting == null
15187                    || filterAppAccessLPr(
15188                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15189                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15190            }
15191
15192            PackageSetting installerPackageSetting;
15193            if (installerPackageName != null) {
15194                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15195                if (installerPackageSetting == null) {
15196                    throw new IllegalArgumentException("Unknown installer package: "
15197                            + installerPackageName);
15198                }
15199            } else {
15200                installerPackageSetting = null;
15201            }
15202
15203            Signature[] callerSignature;
15204            Object obj = mSettings.getUserIdLPr(callingUid);
15205            if (obj != null) {
15206                if (obj instanceof SharedUserSetting) {
15207                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15208                } else if (obj instanceof PackageSetting) {
15209                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15210                } else {
15211                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15212                }
15213            } else {
15214                throw new SecurityException("Unknown calling UID: " + callingUid);
15215            }
15216
15217            // Verify: can't set installerPackageName to a package that is
15218            // not signed with the same cert as the caller.
15219            if (installerPackageSetting != null) {
15220                if (compareSignatures(callerSignature,
15221                        installerPackageSetting.signatures.mSignatures)
15222                        != PackageManager.SIGNATURE_MATCH) {
15223                    throw new SecurityException(
15224                            "Caller does not have same cert as new installer package "
15225                            + installerPackageName);
15226                }
15227            }
15228
15229            // Verify: if target already has an installer package, it must
15230            // be signed with the same cert as the caller.
15231            if (targetPackageSetting.installerPackageName != null) {
15232                PackageSetting setting = mSettings.mPackages.get(
15233                        targetPackageSetting.installerPackageName);
15234                // If the currently set package isn't valid, then it's always
15235                // okay to change it.
15236                if (setting != null) {
15237                    if (compareSignatures(callerSignature,
15238                            setting.signatures.mSignatures)
15239                            != PackageManager.SIGNATURE_MATCH) {
15240                        throw new SecurityException(
15241                                "Caller does not have same cert as old installer package "
15242                                + targetPackageSetting.installerPackageName);
15243                    }
15244                }
15245            }
15246
15247            // Okay!
15248            targetPackageSetting.installerPackageName = installerPackageName;
15249            if (installerPackageName != null) {
15250                mSettings.mInstallerPackages.add(installerPackageName);
15251            }
15252            scheduleWriteSettingsLocked();
15253        }
15254    }
15255
15256    @Override
15257    public void setApplicationCategoryHint(String packageName, int categoryHint,
15258            String callerPackageName) {
15259        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15260            throw new SecurityException("Instant applications don't have access to this method");
15261        }
15262        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15263                callerPackageName);
15264        synchronized (mPackages) {
15265            PackageSetting ps = mSettings.mPackages.get(packageName);
15266            if (ps == null) {
15267                throw new IllegalArgumentException("Unknown target package " + packageName);
15268            }
15269            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15270                throw new IllegalArgumentException("Unknown target package " + packageName);
15271            }
15272            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15273                throw new IllegalArgumentException("Calling package " + callerPackageName
15274                        + " is not installer for " + packageName);
15275            }
15276
15277            if (ps.categoryHint != categoryHint) {
15278                ps.categoryHint = categoryHint;
15279                scheduleWriteSettingsLocked();
15280            }
15281        }
15282    }
15283
15284    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15285        // Queue up an async operation since the package installation may take a little while.
15286        mHandler.post(new Runnable() {
15287            public void run() {
15288                mHandler.removeCallbacks(this);
15289                 // Result object to be returned
15290                PackageInstalledInfo res = new PackageInstalledInfo();
15291                res.setReturnCode(currentStatus);
15292                res.uid = -1;
15293                res.pkg = null;
15294                res.removedInfo = null;
15295                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15296                    args.doPreInstall(res.returnCode);
15297                    synchronized (mInstallLock) {
15298                        installPackageTracedLI(args, res);
15299                    }
15300                    args.doPostInstall(res.returnCode, res.uid);
15301                }
15302
15303                // A restore should be performed at this point if (a) the install
15304                // succeeded, (b) the operation is not an update, and (c) the new
15305                // package has not opted out of backup participation.
15306                final boolean update = res.removedInfo != null
15307                        && res.removedInfo.removedPackage != null;
15308                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15309                boolean doRestore = !update
15310                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15311
15312                // Set up the post-install work request bookkeeping.  This will be used
15313                // and cleaned up by the post-install event handling regardless of whether
15314                // there's a restore pass performed.  Token values are >= 1.
15315                int token;
15316                if (mNextInstallToken < 0) mNextInstallToken = 1;
15317                token = mNextInstallToken++;
15318
15319                PostInstallData data = new PostInstallData(args, res);
15320                mRunningInstalls.put(token, data);
15321                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15322
15323                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15324                    // Pass responsibility to the Backup Manager.  It will perform a
15325                    // restore if appropriate, then pass responsibility back to the
15326                    // Package Manager to run the post-install observer callbacks
15327                    // and broadcasts.
15328                    IBackupManager bm = IBackupManager.Stub.asInterface(
15329                            ServiceManager.getService(Context.BACKUP_SERVICE));
15330                    if (bm != null) {
15331                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15332                                + " to BM for possible restore");
15333                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15334                        try {
15335                            // TODO: http://b/22388012
15336                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15337                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15338                            } else {
15339                                doRestore = false;
15340                            }
15341                        } catch (RemoteException e) {
15342                            // can't happen; the backup manager is local
15343                        } catch (Exception e) {
15344                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15345                            doRestore = false;
15346                        }
15347                    } else {
15348                        Slog.e(TAG, "Backup Manager not found!");
15349                        doRestore = false;
15350                    }
15351                }
15352
15353                if (!doRestore) {
15354                    // No restore possible, or the Backup Manager was mysteriously not
15355                    // available -- just fire the post-install work request directly.
15356                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15357
15358                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15359
15360                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15361                    mHandler.sendMessage(msg);
15362                }
15363            }
15364        });
15365    }
15366
15367    /**
15368     * Callback from PackageSettings whenever an app is first transitioned out of the
15369     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15370     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15371     * here whether the app is the target of an ongoing install, and only send the
15372     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15373     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15374     * handling.
15375     */
15376    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15377        // Serialize this with the rest of the install-process message chain.  In the
15378        // restore-at-install case, this Runnable will necessarily run before the
15379        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15380        // are coherent.  In the non-restore case, the app has already completed install
15381        // and been launched through some other means, so it is not in a problematic
15382        // state for observers to see the FIRST_LAUNCH signal.
15383        mHandler.post(new Runnable() {
15384            @Override
15385            public void run() {
15386                for (int i = 0; i < mRunningInstalls.size(); i++) {
15387                    final PostInstallData data = mRunningInstalls.valueAt(i);
15388                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15389                        continue;
15390                    }
15391                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15392                        // right package; but is it for the right user?
15393                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15394                            if (userId == data.res.newUsers[uIndex]) {
15395                                if (DEBUG_BACKUP) {
15396                                    Slog.i(TAG, "Package " + pkgName
15397                                            + " being restored so deferring FIRST_LAUNCH");
15398                                }
15399                                return;
15400                            }
15401                        }
15402                    }
15403                }
15404                // didn't find it, so not being restored
15405                if (DEBUG_BACKUP) {
15406                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15407                }
15408                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15409            }
15410        });
15411    }
15412
15413    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15414        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15415                installerPkg, null, userIds);
15416    }
15417
15418    private abstract class HandlerParams {
15419        private static final int MAX_RETRIES = 4;
15420
15421        /**
15422         * Number of times startCopy() has been attempted and had a non-fatal
15423         * error.
15424         */
15425        private int mRetries = 0;
15426
15427        /** User handle for the user requesting the information or installation. */
15428        private final UserHandle mUser;
15429        String traceMethod;
15430        int traceCookie;
15431
15432        HandlerParams(UserHandle user) {
15433            mUser = user;
15434        }
15435
15436        UserHandle getUser() {
15437            return mUser;
15438        }
15439
15440        HandlerParams setTraceMethod(String traceMethod) {
15441            this.traceMethod = traceMethod;
15442            return this;
15443        }
15444
15445        HandlerParams setTraceCookie(int traceCookie) {
15446            this.traceCookie = traceCookie;
15447            return this;
15448        }
15449
15450        final boolean startCopy() {
15451            boolean res;
15452            try {
15453                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15454
15455                if (++mRetries > MAX_RETRIES) {
15456                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15457                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15458                    handleServiceError();
15459                    return false;
15460                } else {
15461                    handleStartCopy();
15462                    res = true;
15463                }
15464            } catch (RemoteException e) {
15465                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15466                mHandler.sendEmptyMessage(MCS_RECONNECT);
15467                res = false;
15468            }
15469            handleReturnCode();
15470            return res;
15471        }
15472
15473        final void serviceError() {
15474            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15475            handleServiceError();
15476            handleReturnCode();
15477        }
15478
15479        abstract void handleStartCopy() throws RemoteException;
15480        abstract void handleServiceError();
15481        abstract void handleReturnCode();
15482    }
15483
15484    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15485        for (File path : paths) {
15486            try {
15487                mcs.clearDirectory(path.getAbsolutePath());
15488            } catch (RemoteException e) {
15489            }
15490        }
15491    }
15492
15493    static class OriginInfo {
15494        /**
15495         * Location where install is coming from, before it has been
15496         * copied/renamed into place. This could be a single monolithic APK
15497         * file, or a cluster directory. This location may be untrusted.
15498         */
15499        final File file;
15500        final String cid;
15501
15502        /**
15503         * Flag indicating that {@link #file} or {@link #cid} has already been
15504         * staged, meaning downstream users don't need to defensively copy the
15505         * contents.
15506         */
15507        final boolean staged;
15508
15509        /**
15510         * Flag indicating that {@link #file} or {@link #cid} is an already
15511         * installed app that is being moved.
15512         */
15513        final boolean existing;
15514
15515        final String resolvedPath;
15516        final File resolvedFile;
15517
15518        static OriginInfo fromNothing() {
15519            return new OriginInfo(null, null, false, false);
15520        }
15521
15522        static OriginInfo fromUntrustedFile(File file) {
15523            return new OriginInfo(file, null, false, false);
15524        }
15525
15526        static OriginInfo fromExistingFile(File file) {
15527            return new OriginInfo(file, null, false, true);
15528        }
15529
15530        static OriginInfo fromStagedFile(File file) {
15531            return new OriginInfo(file, null, true, false);
15532        }
15533
15534        static OriginInfo fromStagedContainer(String cid) {
15535            return new OriginInfo(null, cid, true, false);
15536        }
15537
15538        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15539            this.file = file;
15540            this.cid = cid;
15541            this.staged = staged;
15542            this.existing = existing;
15543
15544            if (cid != null) {
15545                resolvedPath = PackageHelper.getSdDir(cid);
15546                resolvedFile = new File(resolvedPath);
15547            } else if (file != null) {
15548                resolvedPath = file.getAbsolutePath();
15549                resolvedFile = file;
15550            } else {
15551                resolvedPath = null;
15552                resolvedFile = null;
15553            }
15554        }
15555    }
15556
15557    static class MoveInfo {
15558        final int moveId;
15559        final String fromUuid;
15560        final String toUuid;
15561        final String packageName;
15562        final String dataAppName;
15563        final int appId;
15564        final String seinfo;
15565        final int targetSdkVersion;
15566
15567        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15568                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15569            this.moveId = moveId;
15570            this.fromUuid = fromUuid;
15571            this.toUuid = toUuid;
15572            this.packageName = packageName;
15573            this.dataAppName = dataAppName;
15574            this.appId = appId;
15575            this.seinfo = seinfo;
15576            this.targetSdkVersion = targetSdkVersion;
15577        }
15578    }
15579
15580    static class VerificationInfo {
15581        /** A constant used to indicate that a uid value is not present. */
15582        public static final int NO_UID = -1;
15583
15584        /** URI referencing where the package was downloaded from. */
15585        final Uri originatingUri;
15586
15587        /** HTTP referrer URI associated with the originatingURI. */
15588        final Uri referrer;
15589
15590        /** UID of the application that the install request originated from. */
15591        final int originatingUid;
15592
15593        /** UID of application requesting the install */
15594        final int installerUid;
15595
15596        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15597            this.originatingUri = originatingUri;
15598            this.referrer = referrer;
15599            this.originatingUid = originatingUid;
15600            this.installerUid = installerUid;
15601        }
15602    }
15603
15604    class InstallParams extends HandlerParams {
15605        final OriginInfo origin;
15606        final MoveInfo move;
15607        final IPackageInstallObserver2 observer;
15608        int installFlags;
15609        final String installerPackageName;
15610        final String volumeUuid;
15611        private InstallArgs mArgs;
15612        private int mRet;
15613        final String packageAbiOverride;
15614        final String[] grantedRuntimePermissions;
15615        final VerificationInfo verificationInfo;
15616        final Certificate[][] certificates;
15617        final int installReason;
15618
15619        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15620                int installFlags, String installerPackageName, String volumeUuid,
15621                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15622                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15623            super(user);
15624            this.origin = origin;
15625            this.move = move;
15626            this.observer = observer;
15627            this.installFlags = installFlags;
15628            this.installerPackageName = installerPackageName;
15629            this.volumeUuid = volumeUuid;
15630            this.verificationInfo = verificationInfo;
15631            this.packageAbiOverride = packageAbiOverride;
15632            this.grantedRuntimePermissions = grantedPermissions;
15633            this.certificates = certificates;
15634            this.installReason = installReason;
15635        }
15636
15637        @Override
15638        public String toString() {
15639            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15640                    + " file=" + origin.file + " cid=" + origin.cid + "}";
15641        }
15642
15643        private int installLocationPolicy(PackageInfoLite pkgLite) {
15644            String packageName = pkgLite.packageName;
15645            int installLocation = pkgLite.installLocation;
15646            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15647            // reader
15648            synchronized (mPackages) {
15649                // Currently installed package which the new package is attempting to replace or
15650                // null if no such package is installed.
15651                PackageParser.Package installedPkg = mPackages.get(packageName);
15652                // Package which currently owns the data which the new package will own if installed.
15653                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15654                // will be null whereas dataOwnerPkg will contain information about the package
15655                // which was uninstalled while keeping its data.
15656                PackageParser.Package dataOwnerPkg = installedPkg;
15657                if (dataOwnerPkg  == null) {
15658                    PackageSetting ps = mSettings.mPackages.get(packageName);
15659                    if (ps != null) {
15660                        dataOwnerPkg = ps.pkg;
15661                    }
15662                }
15663
15664                if (dataOwnerPkg != null) {
15665                    // If installed, the package will get access to data left on the device by its
15666                    // predecessor. As a security measure, this is permited only if this is not a
15667                    // version downgrade or if the predecessor package is marked as debuggable and
15668                    // a downgrade is explicitly requested.
15669                    //
15670                    // On debuggable platform builds, downgrades are permitted even for
15671                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15672                    // not offer security guarantees and thus it's OK to disable some security
15673                    // mechanisms to make debugging/testing easier on those builds. However, even on
15674                    // debuggable builds downgrades of packages are permitted only if requested via
15675                    // installFlags. This is because we aim to keep the behavior of debuggable
15676                    // platform builds as close as possible to the behavior of non-debuggable
15677                    // platform builds.
15678                    final boolean downgradeRequested =
15679                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15680                    final boolean packageDebuggable =
15681                                (dataOwnerPkg.applicationInfo.flags
15682                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15683                    final boolean downgradePermitted =
15684                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15685                    if (!downgradePermitted) {
15686                        try {
15687                            checkDowngrade(dataOwnerPkg, pkgLite);
15688                        } catch (PackageManagerException e) {
15689                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15690                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15691                        }
15692                    }
15693                }
15694
15695                if (installedPkg != null) {
15696                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15697                        // Check for updated system application.
15698                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15699                            if (onSd) {
15700                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15701                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15702                            }
15703                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15704                        } else {
15705                            if (onSd) {
15706                                // Install flag overrides everything.
15707                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15708                            }
15709                            // If current upgrade specifies particular preference
15710                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15711                                // Application explicitly specified internal.
15712                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15713                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15714                                // App explictly prefers external. Let policy decide
15715                            } else {
15716                                // Prefer previous location
15717                                if (isExternal(installedPkg)) {
15718                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15719                                }
15720                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15721                            }
15722                        }
15723                    } else {
15724                        // Invalid install. Return error code
15725                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15726                    }
15727                }
15728            }
15729            // All the special cases have been taken care of.
15730            // Return result based on recommended install location.
15731            if (onSd) {
15732                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15733            }
15734            return pkgLite.recommendedInstallLocation;
15735        }
15736
15737        /*
15738         * Invoke remote method to get package information and install
15739         * location values. Override install location based on default
15740         * policy if needed and then create install arguments based
15741         * on the install location.
15742         */
15743        public void handleStartCopy() throws RemoteException {
15744            int ret = PackageManager.INSTALL_SUCCEEDED;
15745
15746            // If we're already staged, we've firmly committed to an install location
15747            if (origin.staged) {
15748                if (origin.file != null) {
15749                    installFlags |= PackageManager.INSTALL_INTERNAL;
15750                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15751                } else if (origin.cid != null) {
15752                    installFlags |= PackageManager.INSTALL_EXTERNAL;
15753                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
15754                } else {
15755                    throw new IllegalStateException("Invalid stage location");
15756                }
15757            }
15758
15759            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15760            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15761            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15762            PackageInfoLite pkgLite = null;
15763
15764            if (onInt && onSd) {
15765                // Check if both bits are set.
15766                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15767                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15768            } else if (onSd && ephemeral) {
15769                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15770                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15771            } else {
15772                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15773                        packageAbiOverride);
15774
15775                if (DEBUG_EPHEMERAL && ephemeral) {
15776                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15777                }
15778
15779                /*
15780                 * If we have too little free space, try to free cache
15781                 * before giving up.
15782                 */
15783                if (!origin.staged && pkgLite.recommendedInstallLocation
15784                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15785                    // TODO: focus freeing disk space on the target device
15786                    final StorageManager storage = StorageManager.from(mContext);
15787                    final long lowThreshold = storage.getStorageLowBytes(
15788                            Environment.getDataDirectory());
15789
15790                    final long sizeBytes = mContainerService.calculateInstalledSize(
15791                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
15792
15793                    try {
15794                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15795                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15796                                installFlags, packageAbiOverride);
15797                    } catch (InstallerException e) {
15798                        Slog.w(TAG, "Failed to free cache", e);
15799                    }
15800
15801                    /*
15802                     * The cache free must have deleted the file we
15803                     * downloaded to install.
15804                     *
15805                     * TODO: fix the "freeCache" call to not delete
15806                     *       the file we care about.
15807                     */
15808                    if (pkgLite.recommendedInstallLocation
15809                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15810                        pkgLite.recommendedInstallLocation
15811                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15812                    }
15813                }
15814            }
15815
15816            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15817                int loc = pkgLite.recommendedInstallLocation;
15818                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15819                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15820                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15821                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15822                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15823                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15824                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15825                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15826                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15827                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15828                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15829                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15830                } else {
15831                    // Override with defaults if needed.
15832                    loc = installLocationPolicy(pkgLite);
15833                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15834                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15835                    } else if (!onSd && !onInt) {
15836                        // Override install location with flags
15837                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15838                            // Set the flag to install on external media.
15839                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15840                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15841                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15842                            if (DEBUG_EPHEMERAL) {
15843                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15844                            }
15845                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15846                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15847                                    |PackageManager.INSTALL_INTERNAL);
15848                        } else {
15849                            // Make sure the flag for installing on external
15850                            // media is unset
15851                            installFlags |= PackageManager.INSTALL_INTERNAL;
15852                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15853                        }
15854                    }
15855                }
15856            }
15857
15858            final InstallArgs args = createInstallArgs(this);
15859            mArgs = args;
15860
15861            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15862                // TODO: http://b/22976637
15863                // Apps installed for "all" users use the device owner to verify the app
15864                UserHandle verifierUser = getUser();
15865                if (verifierUser == UserHandle.ALL) {
15866                    verifierUser = UserHandle.SYSTEM;
15867                }
15868
15869                /*
15870                 * Determine if we have any installed package verifiers. If we
15871                 * do, then we'll defer to them to verify the packages.
15872                 */
15873                final int requiredUid = mRequiredVerifierPackage == null ? -1
15874                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15875                                verifierUser.getIdentifier());
15876                final int installerUid =
15877                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15878                if (!origin.existing && requiredUid != -1
15879                        && isVerificationEnabled(
15880                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15881                    final Intent verification = new Intent(
15882                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15883                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15884                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15885                            PACKAGE_MIME_TYPE);
15886                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15887
15888                    // Query all live verifiers based on current user state
15889                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15890                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
15891
15892                    if (DEBUG_VERIFY) {
15893                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15894                                + verification.toString() + " with " + pkgLite.verifiers.length
15895                                + " optional verifiers");
15896                    }
15897
15898                    final int verificationId = mPendingVerificationToken++;
15899
15900                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15901
15902                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15903                            installerPackageName);
15904
15905                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15906                            installFlags);
15907
15908                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15909                            pkgLite.packageName);
15910
15911                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15912                            pkgLite.versionCode);
15913
15914                    if (verificationInfo != null) {
15915                        if (verificationInfo.originatingUri != null) {
15916                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15917                                    verificationInfo.originatingUri);
15918                        }
15919                        if (verificationInfo.referrer != null) {
15920                            verification.putExtra(Intent.EXTRA_REFERRER,
15921                                    verificationInfo.referrer);
15922                        }
15923                        if (verificationInfo.originatingUid >= 0) {
15924                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15925                                    verificationInfo.originatingUid);
15926                        }
15927                        if (verificationInfo.installerUid >= 0) {
15928                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15929                                    verificationInfo.installerUid);
15930                        }
15931                    }
15932
15933                    final PackageVerificationState verificationState = new PackageVerificationState(
15934                            requiredUid, args);
15935
15936                    mPendingVerification.append(verificationId, verificationState);
15937
15938                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15939                            receivers, verificationState);
15940
15941                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15942                    final long idleDuration = getVerificationTimeout();
15943
15944                    /*
15945                     * If any sufficient verifiers were listed in the package
15946                     * manifest, attempt to ask them.
15947                     */
15948                    if (sufficientVerifiers != null) {
15949                        final int N = sufficientVerifiers.size();
15950                        if (N == 0) {
15951                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15952                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15953                        } else {
15954                            for (int i = 0; i < N; i++) {
15955                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15956                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15957                                        verifierComponent.getPackageName(), idleDuration,
15958                                        verifierUser.getIdentifier(), false, "package verifier");
15959
15960                                final Intent sufficientIntent = new Intent(verification);
15961                                sufficientIntent.setComponent(verifierComponent);
15962                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15963                            }
15964                        }
15965                    }
15966
15967                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15968                            mRequiredVerifierPackage, receivers);
15969                    if (ret == PackageManager.INSTALL_SUCCEEDED
15970                            && mRequiredVerifierPackage != null) {
15971                        Trace.asyncTraceBegin(
15972                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15973                        /*
15974                         * Send the intent to the required verification agent,
15975                         * but only start the verification timeout after the
15976                         * target BroadcastReceivers have run.
15977                         */
15978                        verification.setComponent(requiredVerifierComponent);
15979                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15980                                mRequiredVerifierPackage, idleDuration,
15981                                verifierUser.getIdentifier(), false, "package verifier");
15982                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15983                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15984                                new BroadcastReceiver() {
15985                                    @Override
15986                                    public void onReceive(Context context, Intent intent) {
15987                                        final Message msg = mHandler
15988                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15989                                        msg.arg1 = verificationId;
15990                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15991                                    }
15992                                }, null, 0, null, null);
15993
15994                        /*
15995                         * We don't want the copy to proceed until verification
15996                         * succeeds, so null out this field.
15997                         */
15998                        mArgs = null;
15999                    }
16000                } else {
16001                    /*
16002                     * No package verification is enabled, so immediately start
16003                     * the remote call to initiate copy using temporary file.
16004                     */
16005                    ret = args.copyApk(mContainerService, true);
16006                }
16007            }
16008
16009            mRet = ret;
16010        }
16011
16012        @Override
16013        void handleReturnCode() {
16014            // If mArgs is null, then MCS couldn't be reached. When it
16015            // reconnects, it will try again to install. At that point, this
16016            // will succeed.
16017            if (mArgs != null) {
16018                processPendingInstall(mArgs, mRet);
16019            }
16020        }
16021
16022        @Override
16023        void handleServiceError() {
16024            mArgs = createInstallArgs(this);
16025            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16026        }
16027
16028        public boolean isForwardLocked() {
16029            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16030        }
16031    }
16032
16033    /**
16034     * Used during creation of InstallArgs
16035     *
16036     * @param installFlags package installation flags
16037     * @return true if should be installed on external storage
16038     */
16039    private static boolean installOnExternalAsec(int installFlags) {
16040        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16041            return false;
16042        }
16043        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16044            return true;
16045        }
16046        return false;
16047    }
16048
16049    /**
16050     * Used during creation of InstallArgs
16051     *
16052     * @param installFlags package installation flags
16053     * @return true if should be installed as forward locked
16054     */
16055    private static boolean installForwardLocked(int installFlags) {
16056        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16057    }
16058
16059    private InstallArgs createInstallArgs(InstallParams params) {
16060        if (params.move != null) {
16061            return new MoveInstallArgs(params);
16062        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16063            return new AsecInstallArgs(params);
16064        } else {
16065            return new FileInstallArgs(params);
16066        }
16067    }
16068
16069    /**
16070     * Create args that describe an existing installed package. Typically used
16071     * when cleaning up old installs, or used as a move source.
16072     */
16073    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16074            String resourcePath, String[] instructionSets) {
16075        final boolean isInAsec;
16076        if (installOnExternalAsec(installFlags)) {
16077            /* Apps on SD card are always in ASEC containers. */
16078            isInAsec = true;
16079        } else if (installForwardLocked(installFlags)
16080                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16081            /*
16082             * Forward-locked apps are only in ASEC containers if they're the
16083             * new style
16084             */
16085            isInAsec = true;
16086        } else {
16087            isInAsec = false;
16088        }
16089
16090        if (isInAsec) {
16091            return new AsecInstallArgs(codePath, instructionSets,
16092                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16093        } else {
16094            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16095        }
16096    }
16097
16098    static abstract class InstallArgs {
16099        /** @see InstallParams#origin */
16100        final OriginInfo origin;
16101        /** @see InstallParams#move */
16102        final MoveInfo move;
16103
16104        final IPackageInstallObserver2 observer;
16105        // Always refers to PackageManager flags only
16106        final int installFlags;
16107        final String installerPackageName;
16108        final String volumeUuid;
16109        final UserHandle user;
16110        final String abiOverride;
16111        final String[] installGrantPermissions;
16112        /** If non-null, drop an async trace when the install completes */
16113        final String traceMethod;
16114        final int traceCookie;
16115        final Certificate[][] certificates;
16116        final int installReason;
16117
16118        // The list of instruction sets supported by this app. This is currently
16119        // only used during the rmdex() phase to clean up resources. We can get rid of this
16120        // if we move dex files under the common app path.
16121        /* nullable */ String[] instructionSets;
16122
16123        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16124                int installFlags, String installerPackageName, String volumeUuid,
16125                UserHandle user, String[] instructionSets,
16126                String abiOverride, String[] installGrantPermissions,
16127                String traceMethod, int traceCookie, Certificate[][] certificates,
16128                int installReason) {
16129            this.origin = origin;
16130            this.move = move;
16131            this.installFlags = installFlags;
16132            this.observer = observer;
16133            this.installerPackageName = installerPackageName;
16134            this.volumeUuid = volumeUuid;
16135            this.user = user;
16136            this.instructionSets = instructionSets;
16137            this.abiOverride = abiOverride;
16138            this.installGrantPermissions = installGrantPermissions;
16139            this.traceMethod = traceMethod;
16140            this.traceCookie = traceCookie;
16141            this.certificates = certificates;
16142            this.installReason = installReason;
16143        }
16144
16145        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16146        abstract int doPreInstall(int status);
16147
16148        /**
16149         * Rename package into final resting place. All paths on the given
16150         * scanned package should be updated to reflect the rename.
16151         */
16152        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16153        abstract int doPostInstall(int status, int uid);
16154
16155        /** @see PackageSettingBase#codePathString */
16156        abstract String getCodePath();
16157        /** @see PackageSettingBase#resourcePathString */
16158        abstract String getResourcePath();
16159
16160        // Need installer lock especially for dex file removal.
16161        abstract void cleanUpResourcesLI();
16162        abstract boolean doPostDeleteLI(boolean delete);
16163
16164        /**
16165         * Called before the source arguments are copied. This is used mostly
16166         * for MoveParams when it needs to read the source file to put it in the
16167         * destination.
16168         */
16169        int doPreCopy() {
16170            return PackageManager.INSTALL_SUCCEEDED;
16171        }
16172
16173        /**
16174         * Called after the source arguments are copied. This is used mostly for
16175         * MoveParams when it needs to read the source file to put it in the
16176         * destination.
16177         */
16178        int doPostCopy(int uid) {
16179            return PackageManager.INSTALL_SUCCEEDED;
16180        }
16181
16182        protected boolean isFwdLocked() {
16183            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16184        }
16185
16186        protected boolean isExternalAsec() {
16187            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16188        }
16189
16190        protected boolean isEphemeral() {
16191            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16192        }
16193
16194        UserHandle getUser() {
16195            return user;
16196        }
16197    }
16198
16199    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16200        if (!allCodePaths.isEmpty()) {
16201            if (instructionSets == null) {
16202                throw new IllegalStateException("instructionSet == null");
16203            }
16204            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16205            for (String codePath : allCodePaths) {
16206                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16207                    try {
16208                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16209                    } catch (InstallerException ignored) {
16210                    }
16211                }
16212            }
16213        }
16214    }
16215
16216    /**
16217     * Logic to handle installation of non-ASEC applications, including copying
16218     * and renaming logic.
16219     */
16220    class FileInstallArgs extends InstallArgs {
16221        private File codeFile;
16222        private File resourceFile;
16223
16224        // Example topology:
16225        // /data/app/com.example/base.apk
16226        // /data/app/com.example/split_foo.apk
16227        // /data/app/com.example/lib/arm/libfoo.so
16228        // /data/app/com.example/lib/arm64/libfoo.so
16229        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16230
16231        /** New install */
16232        FileInstallArgs(InstallParams params) {
16233            super(params.origin, params.move, params.observer, params.installFlags,
16234                    params.installerPackageName, params.volumeUuid,
16235                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16236                    params.grantedRuntimePermissions,
16237                    params.traceMethod, params.traceCookie, params.certificates,
16238                    params.installReason);
16239            if (isFwdLocked()) {
16240                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16241            }
16242        }
16243
16244        /** Existing install */
16245        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16246            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16247                    null, null, null, 0, null /*certificates*/,
16248                    PackageManager.INSTALL_REASON_UNKNOWN);
16249            this.codeFile = (codePath != null) ? new File(codePath) : null;
16250            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16251        }
16252
16253        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16254            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16255            try {
16256                return doCopyApk(imcs, temp);
16257            } finally {
16258                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16259            }
16260        }
16261
16262        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16263            if (origin.staged) {
16264                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16265                codeFile = origin.file;
16266                resourceFile = origin.file;
16267                return PackageManager.INSTALL_SUCCEEDED;
16268            }
16269
16270            try {
16271                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16272                final File tempDir =
16273                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16274                codeFile = tempDir;
16275                resourceFile = tempDir;
16276            } catch (IOException e) {
16277                Slog.w(TAG, "Failed to create copy file: " + e);
16278                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16279            }
16280
16281            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16282                @Override
16283                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16284                    if (!FileUtils.isValidExtFilename(name)) {
16285                        throw new IllegalArgumentException("Invalid filename: " + name);
16286                    }
16287                    try {
16288                        final File file = new File(codeFile, name);
16289                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16290                                O_RDWR | O_CREAT, 0644);
16291                        Os.chmod(file.getAbsolutePath(), 0644);
16292                        return new ParcelFileDescriptor(fd);
16293                    } catch (ErrnoException e) {
16294                        throw new RemoteException("Failed to open: " + e.getMessage());
16295                    }
16296                }
16297            };
16298
16299            int ret = PackageManager.INSTALL_SUCCEEDED;
16300            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16301            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16302                Slog.e(TAG, "Failed to copy package");
16303                return ret;
16304            }
16305
16306            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16307            NativeLibraryHelper.Handle handle = null;
16308            try {
16309                handle = NativeLibraryHelper.Handle.create(codeFile);
16310                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16311                        abiOverride);
16312            } catch (IOException e) {
16313                Slog.e(TAG, "Copying native libraries failed", e);
16314                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16315            } finally {
16316                IoUtils.closeQuietly(handle);
16317            }
16318
16319            return ret;
16320        }
16321
16322        int doPreInstall(int status) {
16323            if (status != PackageManager.INSTALL_SUCCEEDED) {
16324                cleanUp();
16325            }
16326            return status;
16327        }
16328
16329        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16330            if (status != PackageManager.INSTALL_SUCCEEDED) {
16331                cleanUp();
16332                return false;
16333            }
16334
16335            final File targetDir = codeFile.getParentFile();
16336            final File beforeCodeFile = codeFile;
16337            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16338
16339            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16340            try {
16341                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16342            } catch (ErrnoException e) {
16343                Slog.w(TAG, "Failed to rename", e);
16344                return false;
16345            }
16346
16347            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16348                Slog.w(TAG, "Failed to restorecon");
16349                return false;
16350            }
16351
16352            // Reflect the rename internally
16353            codeFile = afterCodeFile;
16354            resourceFile = afterCodeFile;
16355
16356            // Reflect the rename in scanned details
16357            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16358            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16359                    afterCodeFile, pkg.baseCodePath));
16360            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16361                    afterCodeFile, pkg.splitCodePaths));
16362
16363            // Reflect the rename in app info
16364            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16365            pkg.setApplicationInfoCodePath(pkg.codePath);
16366            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16367            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16368            pkg.setApplicationInfoResourcePath(pkg.codePath);
16369            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16370            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16371
16372            return true;
16373        }
16374
16375        int doPostInstall(int status, int uid) {
16376            if (status != PackageManager.INSTALL_SUCCEEDED) {
16377                cleanUp();
16378            }
16379            return status;
16380        }
16381
16382        @Override
16383        String getCodePath() {
16384            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16385        }
16386
16387        @Override
16388        String getResourcePath() {
16389            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16390        }
16391
16392        private boolean cleanUp() {
16393            if (codeFile == null || !codeFile.exists()) {
16394                return false;
16395            }
16396
16397            removeCodePathLI(codeFile);
16398
16399            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16400                resourceFile.delete();
16401            }
16402
16403            return true;
16404        }
16405
16406        void cleanUpResourcesLI() {
16407            // Try enumerating all code paths before deleting
16408            List<String> allCodePaths = Collections.EMPTY_LIST;
16409            if (codeFile != null && codeFile.exists()) {
16410                try {
16411                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16412                    allCodePaths = pkg.getAllCodePaths();
16413                } catch (PackageParserException e) {
16414                    // Ignored; we tried our best
16415                }
16416            }
16417
16418            cleanUp();
16419            removeDexFiles(allCodePaths, instructionSets);
16420        }
16421
16422        boolean doPostDeleteLI(boolean delete) {
16423            // XXX err, shouldn't we respect the delete flag?
16424            cleanUpResourcesLI();
16425            return true;
16426        }
16427    }
16428
16429    private boolean isAsecExternal(String cid) {
16430        final String asecPath = PackageHelper.getSdFilesystem(cid);
16431        return !asecPath.startsWith(mAsecInternalPath);
16432    }
16433
16434    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16435            PackageManagerException {
16436        if (copyRet < 0) {
16437            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16438                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16439                throw new PackageManagerException(copyRet, message);
16440            }
16441        }
16442    }
16443
16444    /**
16445     * Extract the StorageManagerService "container ID" from the full code path of an
16446     * .apk.
16447     */
16448    static String cidFromCodePath(String fullCodePath) {
16449        int eidx = fullCodePath.lastIndexOf("/");
16450        String subStr1 = fullCodePath.substring(0, eidx);
16451        int sidx = subStr1.lastIndexOf("/");
16452        return subStr1.substring(sidx+1, eidx);
16453    }
16454
16455    /**
16456     * Logic to handle installation of ASEC applications, including copying and
16457     * renaming logic.
16458     */
16459    class AsecInstallArgs extends InstallArgs {
16460        static final String RES_FILE_NAME = "pkg.apk";
16461        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16462
16463        String cid;
16464        String packagePath;
16465        String resourcePath;
16466
16467        /** New install */
16468        AsecInstallArgs(InstallParams params) {
16469            super(params.origin, params.move, params.observer, params.installFlags,
16470                    params.installerPackageName, params.volumeUuid,
16471                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16472                    params.grantedRuntimePermissions,
16473                    params.traceMethod, params.traceCookie, params.certificates,
16474                    params.installReason);
16475        }
16476
16477        /** Existing install */
16478        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16479                        boolean isExternal, boolean isForwardLocked) {
16480            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16481                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16482                    instructionSets, null, null, null, 0, null /*certificates*/,
16483                    PackageManager.INSTALL_REASON_UNKNOWN);
16484            // Hackily pretend we're still looking at a full code path
16485            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16486                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16487            }
16488
16489            // Extract cid from fullCodePath
16490            int eidx = fullCodePath.lastIndexOf("/");
16491            String subStr1 = fullCodePath.substring(0, eidx);
16492            int sidx = subStr1.lastIndexOf("/");
16493            cid = subStr1.substring(sidx+1, eidx);
16494            setMountPath(subStr1);
16495        }
16496
16497        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16498            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16499                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16500                    instructionSets, null, null, null, 0, null /*certificates*/,
16501                    PackageManager.INSTALL_REASON_UNKNOWN);
16502            this.cid = cid;
16503            setMountPath(PackageHelper.getSdDir(cid));
16504        }
16505
16506        void createCopyFile() {
16507            cid = mInstallerService.allocateExternalStageCidLegacy();
16508        }
16509
16510        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16511            if (origin.staged && origin.cid != null) {
16512                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16513                cid = origin.cid;
16514                setMountPath(PackageHelper.getSdDir(cid));
16515                return PackageManager.INSTALL_SUCCEEDED;
16516            }
16517
16518            if (temp) {
16519                createCopyFile();
16520            } else {
16521                /*
16522                 * Pre-emptively destroy the container since it's destroyed if
16523                 * copying fails due to it existing anyway.
16524                 */
16525                PackageHelper.destroySdDir(cid);
16526            }
16527
16528            final String newMountPath = imcs.copyPackageToContainer(
16529                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16530                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16531
16532            if (newMountPath != null) {
16533                setMountPath(newMountPath);
16534                return PackageManager.INSTALL_SUCCEEDED;
16535            } else {
16536                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16537            }
16538        }
16539
16540        @Override
16541        String getCodePath() {
16542            return packagePath;
16543        }
16544
16545        @Override
16546        String getResourcePath() {
16547            return resourcePath;
16548        }
16549
16550        int doPreInstall(int status) {
16551            if (status != PackageManager.INSTALL_SUCCEEDED) {
16552                // Destroy container
16553                PackageHelper.destroySdDir(cid);
16554            } else {
16555                boolean mounted = PackageHelper.isContainerMounted(cid);
16556                if (!mounted) {
16557                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16558                            Process.SYSTEM_UID);
16559                    if (newMountPath != null) {
16560                        setMountPath(newMountPath);
16561                    } else {
16562                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16563                    }
16564                }
16565            }
16566            return status;
16567        }
16568
16569        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16570            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16571            String newMountPath = null;
16572            if (PackageHelper.isContainerMounted(cid)) {
16573                // Unmount the container
16574                if (!PackageHelper.unMountSdDir(cid)) {
16575                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16576                    return false;
16577                }
16578            }
16579            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16580                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16581                        " which might be stale. Will try to clean up.");
16582                // Clean up the stale container and proceed to recreate.
16583                if (!PackageHelper.destroySdDir(newCacheId)) {
16584                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16585                    return false;
16586                }
16587                // Successfully cleaned up stale container. Try to rename again.
16588                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16589                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16590                            + " inspite of cleaning it up.");
16591                    return false;
16592                }
16593            }
16594            if (!PackageHelper.isContainerMounted(newCacheId)) {
16595                Slog.w(TAG, "Mounting container " + newCacheId);
16596                newMountPath = PackageHelper.mountSdDir(newCacheId,
16597                        getEncryptKey(), Process.SYSTEM_UID);
16598            } else {
16599                newMountPath = PackageHelper.getSdDir(newCacheId);
16600            }
16601            if (newMountPath == null) {
16602                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16603                return false;
16604            }
16605            Log.i(TAG, "Succesfully renamed " + cid +
16606                    " to " + newCacheId +
16607                    " at new path: " + newMountPath);
16608            cid = newCacheId;
16609
16610            final File beforeCodeFile = new File(packagePath);
16611            setMountPath(newMountPath);
16612            final File afterCodeFile = new File(packagePath);
16613
16614            // Reflect the rename in scanned details
16615            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16616            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16617                    afterCodeFile, pkg.baseCodePath));
16618            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16619                    afterCodeFile, pkg.splitCodePaths));
16620
16621            // Reflect the rename in app info
16622            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16623            pkg.setApplicationInfoCodePath(pkg.codePath);
16624            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16625            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16626            pkg.setApplicationInfoResourcePath(pkg.codePath);
16627            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16628            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16629
16630            return true;
16631        }
16632
16633        private void setMountPath(String mountPath) {
16634            final File mountFile = new File(mountPath);
16635
16636            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16637            if (monolithicFile.exists()) {
16638                packagePath = monolithicFile.getAbsolutePath();
16639                if (isFwdLocked()) {
16640                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16641                } else {
16642                    resourcePath = packagePath;
16643                }
16644            } else {
16645                packagePath = mountFile.getAbsolutePath();
16646                resourcePath = packagePath;
16647            }
16648        }
16649
16650        int doPostInstall(int status, int uid) {
16651            if (status != PackageManager.INSTALL_SUCCEEDED) {
16652                cleanUp();
16653            } else {
16654                final int groupOwner;
16655                final String protectedFile;
16656                if (isFwdLocked()) {
16657                    groupOwner = UserHandle.getSharedAppGid(uid);
16658                    protectedFile = RES_FILE_NAME;
16659                } else {
16660                    groupOwner = -1;
16661                    protectedFile = null;
16662                }
16663
16664                if (uid < Process.FIRST_APPLICATION_UID
16665                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16666                    Slog.e(TAG, "Failed to finalize " + cid);
16667                    PackageHelper.destroySdDir(cid);
16668                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16669                }
16670
16671                boolean mounted = PackageHelper.isContainerMounted(cid);
16672                if (!mounted) {
16673                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
16674                }
16675            }
16676            return status;
16677        }
16678
16679        private void cleanUp() {
16680            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
16681
16682            // Destroy secure container
16683            PackageHelper.destroySdDir(cid);
16684        }
16685
16686        private List<String> getAllCodePaths() {
16687            final File codeFile = new File(getCodePath());
16688            if (codeFile != null && codeFile.exists()) {
16689                try {
16690                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16691                    return pkg.getAllCodePaths();
16692                } catch (PackageParserException e) {
16693                    // Ignored; we tried our best
16694                }
16695            }
16696            return Collections.EMPTY_LIST;
16697        }
16698
16699        void cleanUpResourcesLI() {
16700            // Enumerate all code paths before deleting
16701            cleanUpResourcesLI(getAllCodePaths());
16702        }
16703
16704        private void cleanUpResourcesLI(List<String> allCodePaths) {
16705            cleanUp();
16706            removeDexFiles(allCodePaths, instructionSets);
16707        }
16708
16709        String getPackageName() {
16710            return getAsecPackageName(cid);
16711        }
16712
16713        boolean doPostDeleteLI(boolean delete) {
16714            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
16715            final List<String> allCodePaths = getAllCodePaths();
16716            boolean mounted = PackageHelper.isContainerMounted(cid);
16717            if (mounted) {
16718                // Unmount first
16719                if (PackageHelper.unMountSdDir(cid)) {
16720                    mounted = false;
16721                }
16722            }
16723            if (!mounted && delete) {
16724                cleanUpResourcesLI(allCodePaths);
16725            }
16726            return !mounted;
16727        }
16728
16729        @Override
16730        int doPreCopy() {
16731            if (isFwdLocked()) {
16732                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
16733                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
16734                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16735                }
16736            }
16737
16738            return PackageManager.INSTALL_SUCCEEDED;
16739        }
16740
16741        @Override
16742        int doPostCopy(int uid) {
16743            if (isFwdLocked()) {
16744                if (uid < Process.FIRST_APPLICATION_UID
16745                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
16746                                RES_FILE_NAME)) {
16747                    Slog.e(TAG, "Failed to finalize " + cid);
16748                    PackageHelper.destroySdDir(cid);
16749                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16750                }
16751            }
16752
16753            return PackageManager.INSTALL_SUCCEEDED;
16754        }
16755    }
16756
16757    /**
16758     * Logic to handle movement of existing installed applications.
16759     */
16760    class MoveInstallArgs extends InstallArgs {
16761        private File codeFile;
16762        private File resourceFile;
16763
16764        /** New install */
16765        MoveInstallArgs(InstallParams params) {
16766            super(params.origin, params.move, params.observer, params.installFlags,
16767                    params.installerPackageName, params.volumeUuid,
16768                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16769                    params.grantedRuntimePermissions,
16770                    params.traceMethod, params.traceCookie, params.certificates,
16771                    params.installReason);
16772        }
16773
16774        int copyApk(IMediaContainerService imcs, boolean temp) {
16775            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16776                    + move.fromUuid + " to " + move.toUuid);
16777            synchronized (mInstaller) {
16778                try {
16779                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16780                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16781                } catch (InstallerException e) {
16782                    Slog.w(TAG, "Failed to move app", e);
16783                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16784                }
16785            }
16786
16787            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16788            resourceFile = codeFile;
16789            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16790
16791            return PackageManager.INSTALL_SUCCEEDED;
16792        }
16793
16794        int doPreInstall(int status) {
16795            if (status != PackageManager.INSTALL_SUCCEEDED) {
16796                cleanUp(move.toUuid);
16797            }
16798            return status;
16799        }
16800
16801        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16802            if (status != PackageManager.INSTALL_SUCCEEDED) {
16803                cleanUp(move.toUuid);
16804                return false;
16805            }
16806
16807            // Reflect the move in app info
16808            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16809            pkg.setApplicationInfoCodePath(pkg.codePath);
16810            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16811            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16812            pkg.setApplicationInfoResourcePath(pkg.codePath);
16813            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16814            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16815
16816            return true;
16817        }
16818
16819        int doPostInstall(int status, int uid) {
16820            if (status == PackageManager.INSTALL_SUCCEEDED) {
16821                cleanUp(move.fromUuid);
16822            } else {
16823                cleanUp(move.toUuid);
16824            }
16825            return status;
16826        }
16827
16828        @Override
16829        String getCodePath() {
16830            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16831        }
16832
16833        @Override
16834        String getResourcePath() {
16835            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16836        }
16837
16838        private boolean cleanUp(String volumeUuid) {
16839            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16840                    move.dataAppName);
16841            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16842            final int[] userIds = sUserManager.getUserIds();
16843            synchronized (mInstallLock) {
16844                // Clean up both app data and code
16845                // All package moves are frozen until finished
16846                for (int userId : userIds) {
16847                    try {
16848                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16849                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16850                    } catch (InstallerException e) {
16851                        Slog.w(TAG, String.valueOf(e));
16852                    }
16853                }
16854                removeCodePathLI(codeFile);
16855            }
16856            return true;
16857        }
16858
16859        void cleanUpResourcesLI() {
16860            throw new UnsupportedOperationException();
16861        }
16862
16863        boolean doPostDeleteLI(boolean delete) {
16864            throw new UnsupportedOperationException();
16865        }
16866    }
16867
16868    static String getAsecPackageName(String packageCid) {
16869        int idx = packageCid.lastIndexOf("-");
16870        if (idx == -1) {
16871            return packageCid;
16872        }
16873        return packageCid.substring(0, idx);
16874    }
16875
16876    // Utility method used to create code paths based on package name and available index.
16877    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16878        String idxStr = "";
16879        int idx = 1;
16880        // Fall back to default value of idx=1 if prefix is not
16881        // part of oldCodePath
16882        if (oldCodePath != null) {
16883            String subStr = oldCodePath;
16884            // Drop the suffix right away
16885            if (suffix != null && subStr.endsWith(suffix)) {
16886                subStr = subStr.substring(0, subStr.length() - suffix.length());
16887            }
16888            // If oldCodePath already contains prefix find out the
16889            // ending index to either increment or decrement.
16890            int sidx = subStr.lastIndexOf(prefix);
16891            if (sidx != -1) {
16892                subStr = subStr.substring(sidx + prefix.length());
16893                if (subStr != null) {
16894                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16895                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16896                    }
16897                    try {
16898                        idx = Integer.parseInt(subStr);
16899                        if (idx <= 1) {
16900                            idx++;
16901                        } else {
16902                            idx--;
16903                        }
16904                    } catch(NumberFormatException e) {
16905                    }
16906                }
16907            }
16908        }
16909        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16910        return prefix + idxStr;
16911    }
16912
16913    private File getNextCodePath(File targetDir, String packageName) {
16914        File result;
16915        SecureRandom random = new SecureRandom();
16916        byte[] bytes = new byte[16];
16917        do {
16918            random.nextBytes(bytes);
16919            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16920            result = new File(targetDir, packageName + "-" + suffix);
16921        } while (result.exists());
16922        return result;
16923    }
16924
16925    // Utility method that returns the relative package path with respect
16926    // to the installation directory. Like say for /data/data/com.test-1.apk
16927    // string com.test-1 is returned.
16928    static String deriveCodePathName(String codePath) {
16929        if (codePath == null) {
16930            return null;
16931        }
16932        final File codeFile = new File(codePath);
16933        final String name = codeFile.getName();
16934        if (codeFile.isDirectory()) {
16935            return name;
16936        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16937            final int lastDot = name.lastIndexOf('.');
16938            return name.substring(0, lastDot);
16939        } else {
16940            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16941            return null;
16942        }
16943    }
16944
16945    static class PackageInstalledInfo {
16946        String name;
16947        int uid;
16948        // The set of users that originally had this package installed.
16949        int[] origUsers;
16950        // The set of users that now have this package installed.
16951        int[] newUsers;
16952        PackageParser.Package pkg;
16953        int returnCode;
16954        String returnMsg;
16955        PackageRemovedInfo removedInfo;
16956        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16957
16958        public void setError(int code, String msg) {
16959            setReturnCode(code);
16960            setReturnMessage(msg);
16961            Slog.w(TAG, msg);
16962        }
16963
16964        public void setError(String msg, PackageParserException e) {
16965            setReturnCode(e.error);
16966            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16967            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16968            for (int i = 0; i < childCount; i++) {
16969                addedChildPackages.valueAt(i).setError(msg, e);
16970            }
16971            Slog.w(TAG, msg, e);
16972        }
16973
16974        public void setError(String msg, PackageManagerException e) {
16975            returnCode = e.error;
16976            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16977            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16978            for (int i = 0; i < childCount; i++) {
16979                addedChildPackages.valueAt(i).setError(msg, e);
16980            }
16981            Slog.w(TAG, msg, e);
16982        }
16983
16984        public void setReturnCode(int returnCode) {
16985            this.returnCode = returnCode;
16986            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16987            for (int i = 0; i < childCount; i++) {
16988                addedChildPackages.valueAt(i).returnCode = returnCode;
16989            }
16990        }
16991
16992        private void setReturnMessage(String returnMsg) {
16993            this.returnMsg = returnMsg;
16994            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16995            for (int i = 0; i < childCount; i++) {
16996                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16997            }
16998        }
16999
17000        // In some error cases we want to convey more info back to the observer
17001        String origPackage;
17002        String origPermission;
17003    }
17004
17005    /*
17006     * Install a non-existing package.
17007     */
17008    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17009            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17010            PackageInstalledInfo res, int installReason) {
17011        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17012
17013        // Remember this for later, in case we need to rollback this install
17014        String pkgName = pkg.packageName;
17015
17016        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17017
17018        synchronized(mPackages) {
17019            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17020            if (renamedPackage != null) {
17021                // A package with the same name is already installed, though
17022                // it has been renamed to an older name.  The package we
17023                // are trying to install should be installed as an update to
17024                // the existing one, but that has not been requested, so bail.
17025                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17026                        + " without first uninstalling package running as "
17027                        + renamedPackage);
17028                return;
17029            }
17030            if (mPackages.containsKey(pkgName)) {
17031                // Don't allow installation over an existing package with the same name.
17032                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17033                        + " without first uninstalling.");
17034                return;
17035            }
17036        }
17037
17038        try {
17039            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17040                    System.currentTimeMillis(), user);
17041
17042            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17043
17044            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17045                prepareAppDataAfterInstallLIF(newPackage);
17046
17047            } else {
17048                // Remove package from internal structures, but keep around any
17049                // data that might have already existed
17050                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17051                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17052            }
17053        } catch (PackageManagerException e) {
17054            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17055        }
17056
17057        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17058    }
17059
17060    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17061        // Can't rotate keys during boot or if sharedUser.
17062        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17063                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17064            return false;
17065        }
17066        // app is using upgradeKeySets; make sure all are valid
17067        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17068        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17069        for (int i = 0; i < upgradeKeySets.length; i++) {
17070            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17071                Slog.wtf(TAG, "Package "
17072                         + (oldPs.name != null ? oldPs.name : "<null>")
17073                         + " contains upgrade-key-set reference to unknown key-set: "
17074                         + upgradeKeySets[i]
17075                         + " reverting to signatures check.");
17076                return false;
17077            }
17078        }
17079        return true;
17080    }
17081
17082    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17083        // Upgrade keysets are being used.  Determine if new package has a superset of the
17084        // required keys.
17085        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17086        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17087        for (int i = 0; i < upgradeKeySets.length; i++) {
17088            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17089            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17090                return true;
17091            }
17092        }
17093        return false;
17094    }
17095
17096    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17097        try (DigestInputStream digestStream =
17098                new DigestInputStream(new FileInputStream(file), digest)) {
17099            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17100        }
17101    }
17102
17103    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17104            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17105            int installReason) {
17106        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17107
17108        final PackageParser.Package oldPackage;
17109        final PackageSetting ps;
17110        final String pkgName = pkg.packageName;
17111        final int[] allUsers;
17112        final int[] installedUsers;
17113
17114        synchronized(mPackages) {
17115            oldPackage = mPackages.get(pkgName);
17116            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17117
17118            // don't allow upgrade to target a release SDK from a pre-release SDK
17119            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17120                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17121            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17122                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17123            if (oldTargetsPreRelease
17124                    && !newTargetsPreRelease
17125                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17126                Slog.w(TAG, "Can't install package targeting released sdk");
17127                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17128                return;
17129            }
17130
17131            ps = mSettings.mPackages.get(pkgName);
17132
17133            // verify signatures are valid
17134            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17135                if (!checkUpgradeKeySetLP(ps, pkg)) {
17136                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17137                            "New package not signed by keys specified by upgrade-keysets: "
17138                                    + pkgName);
17139                    return;
17140                }
17141            } else {
17142                // default to original signature matching
17143                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17144                        != PackageManager.SIGNATURE_MATCH) {
17145                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17146                            "New package has a different signature: " + pkgName);
17147                    return;
17148                }
17149            }
17150
17151            // don't allow a system upgrade unless the upgrade hash matches
17152            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17153                byte[] digestBytes = null;
17154                try {
17155                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17156                    updateDigest(digest, new File(pkg.baseCodePath));
17157                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17158                        for (String path : pkg.splitCodePaths) {
17159                            updateDigest(digest, new File(path));
17160                        }
17161                    }
17162                    digestBytes = digest.digest();
17163                } catch (NoSuchAlgorithmException | IOException e) {
17164                    res.setError(INSTALL_FAILED_INVALID_APK,
17165                            "Could not compute hash: " + pkgName);
17166                    return;
17167                }
17168                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17169                    res.setError(INSTALL_FAILED_INVALID_APK,
17170                            "New package fails restrict-update check: " + pkgName);
17171                    return;
17172                }
17173                // retain upgrade restriction
17174                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17175            }
17176
17177            // Check for shared user id changes
17178            String invalidPackageName =
17179                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17180            if (invalidPackageName != null) {
17181                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17182                        "Package " + invalidPackageName + " tried to change user "
17183                                + oldPackage.mSharedUserId);
17184                return;
17185            }
17186
17187            // In case of rollback, remember per-user/profile install state
17188            allUsers = sUserManager.getUserIds();
17189            installedUsers = ps.queryInstalledUsers(allUsers, true);
17190
17191            // don't allow an upgrade from full to ephemeral
17192            if (isInstantApp) {
17193                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17194                    for (int currentUser : allUsers) {
17195                        if (!ps.getInstantApp(currentUser)) {
17196                            // can't downgrade from full to instant
17197                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17198                                    + " for user: " + currentUser);
17199                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17200                            return;
17201                        }
17202                    }
17203                } else if (!ps.getInstantApp(user.getIdentifier())) {
17204                    // can't downgrade from full to instant
17205                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17206                            + " for user: " + user.getIdentifier());
17207                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17208                    return;
17209                }
17210            }
17211        }
17212
17213        // Update what is removed
17214        res.removedInfo = new PackageRemovedInfo(this);
17215        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17216        res.removedInfo.removedPackage = oldPackage.packageName;
17217        res.removedInfo.installerPackageName = ps.installerPackageName;
17218        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17219        res.removedInfo.isUpdate = true;
17220        res.removedInfo.origUsers = installedUsers;
17221        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17222        for (int i = 0; i < installedUsers.length; i++) {
17223            final int userId = installedUsers[i];
17224            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17225        }
17226
17227        final int childCount = (oldPackage.childPackages != null)
17228                ? oldPackage.childPackages.size() : 0;
17229        for (int i = 0; i < childCount; i++) {
17230            boolean childPackageUpdated = false;
17231            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17232            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17233            if (res.addedChildPackages != null) {
17234                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17235                if (childRes != null) {
17236                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17237                    childRes.removedInfo.removedPackage = childPkg.packageName;
17238                    if (childPs != null) {
17239                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17240                    }
17241                    childRes.removedInfo.isUpdate = true;
17242                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17243                    childPackageUpdated = true;
17244                }
17245            }
17246            if (!childPackageUpdated) {
17247                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17248                childRemovedRes.removedPackage = childPkg.packageName;
17249                if (childPs != null) {
17250                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17251                }
17252                childRemovedRes.isUpdate = false;
17253                childRemovedRes.dataRemoved = true;
17254                synchronized (mPackages) {
17255                    if (childPs != null) {
17256                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17257                    }
17258                }
17259                if (res.removedInfo.removedChildPackages == null) {
17260                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17261                }
17262                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17263            }
17264        }
17265
17266        boolean sysPkg = (isSystemApp(oldPackage));
17267        if (sysPkg) {
17268            // Set the system/privileged flags as needed
17269            final boolean privileged =
17270                    (oldPackage.applicationInfo.privateFlags
17271                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17272            final int systemPolicyFlags = policyFlags
17273                    | PackageParser.PARSE_IS_SYSTEM
17274                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17275
17276            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17277                    user, allUsers, installerPackageName, res, installReason);
17278        } else {
17279            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17280                    user, allUsers, installerPackageName, res, installReason);
17281        }
17282    }
17283
17284    @Override
17285    public List<String> getPreviousCodePaths(String packageName) {
17286        final int callingUid = Binder.getCallingUid();
17287        final List<String> result = new ArrayList<>();
17288        if (getInstantAppPackageName(callingUid) != null) {
17289            return result;
17290        }
17291        final PackageSetting ps = mSettings.mPackages.get(packageName);
17292        if (ps != null
17293                && ps.oldCodePaths != null
17294                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17295            result.addAll(ps.oldCodePaths);
17296        }
17297        return result;
17298    }
17299
17300    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17301            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17302            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17303            int installReason) {
17304        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17305                + deletedPackage);
17306
17307        String pkgName = deletedPackage.packageName;
17308        boolean deletedPkg = true;
17309        boolean addedPkg = false;
17310        boolean updatedSettings = false;
17311        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17312        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17313                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17314
17315        final long origUpdateTime = (pkg.mExtras != null)
17316                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17317
17318        // First delete the existing package while retaining the data directory
17319        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17320                res.removedInfo, true, pkg)) {
17321            // If the existing package wasn't successfully deleted
17322            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17323            deletedPkg = false;
17324        } else {
17325            // Successfully deleted the old package; proceed with replace.
17326
17327            // If deleted package lived in a container, give users a chance to
17328            // relinquish resources before killing.
17329            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17330                if (DEBUG_INSTALL) {
17331                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17332                }
17333                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17334                final ArrayList<String> pkgList = new ArrayList<String>(1);
17335                pkgList.add(deletedPackage.applicationInfo.packageName);
17336                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17337            }
17338
17339            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17340                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17341            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17342
17343            try {
17344                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17345                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17346                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17347                        installReason);
17348
17349                // Update the in-memory copy of the previous code paths.
17350                PackageSetting ps = mSettings.mPackages.get(pkgName);
17351                if (!killApp) {
17352                    if (ps.oldCodePaths == null) {
17353                        ps.oldCodePaths = new ArraySet<>();
17354                    }
17355                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17356                    if (deletedPackage.splitCodePaths != null) {
17357                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17358                    }
17359                } else {
17360                    ps.oldCodePaths = null;
17361                }
17362                if (ps.childPackageNames != null) {
17363                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17364                        final String childPkgName = ps.childPackageNames.get(i);
17365                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17366                        childPs.oldCodePaths = ps.oldCodePaths;
17367                    }
17368                }
17369                // set instant app status, but, only if it's explicitly specified
17370                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17371                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17372                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17373                prepareAppDataAfterInstallLIF(newPackage);
17374                addedPkg = true;
17375                mDexManager.notifyPackageUpdated(newPackage.packageName,
17376                        newPackage.baseCodePath, newPackage.splitCodePaths);
17377            } catch (PackageManagerException e) {
17378                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17379            }
17380        }
17381
17382        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17383            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17384
17385            // Revert all internal state mutations and added folders for the failed install
17386            if (addedPkg) {
17387                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17388                        res.removedInfo, true, null);
17389            }
17390
17391            // Restore the old package
17392            if (deletedPkg) {
17393                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17394                File restoreFile = new File(deletedPackage.codePath);
17395                // Parse old package
17396                boolean oldExternal = isExternal(deletedPackage);
17397                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17398                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17399                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17400                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17401                try {
17402                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17403                            null);
17404                } catch (PackageManagerException e) {
17405                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17406                            + e.getMessage());
17407                    return;
17408                }
17409
17410                synchronized (mPackages) {
17411                    // Ensure the installer package name up to date
17412                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17413
17414                    // Update permissions for restored package
17415                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17416
17417                    mSettings.writeLPr();
17418                }
17419
17420                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17421            }
17422        } else {
17423            synchronized (mPackages) {
17424                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17425                if (ps != null) {
17426                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17427                    if (res.removedInfo.removedChildPackages != null) {
17428                        final int childCount = res.removedInfo.removedChildPackages.size();
17429                        // Iterate in reverse as we may modify the collection
17430                        for (int i = childCount - 1; i >= 0; i--) {
17431                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17432                            if (res.addedChildPackages.containsKey(childPackageName)) {
17433                                res.removedInfo.removedChildPackages.removeAt(i);
17434                            } else {
17435                                PackageRemovedInfo childInfo = res.removedInfo
17436                                        .removedChildPackages.valueAt(i);
17437                                childInfo.removedForAllUsers = mPackages.get(
17438                                        childInfo.removedPackage) == null;
17439                            }
17440                        }
17441                    }
17442                }
17443            }
17444        }
17445    }
17446
17447    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17448            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17449            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17450            int installReason) {
17451        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17452                + ", old=" + deletedPackage);
17453
17454        final boolean disabledSystem;
17455
17456        // Remove existing system package
17457        removePackageLI(deletedPackage, true);
17458
17459        synchronized (mPackages) {
17460            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17461        }
17462        if (!disabledSystem) {
17463            // We didn't need to disable the .apk as a current system package,
17464            // which means we are replacing another update that is already
17465            // installed.  We need to make sure to delete the older one's .apk.
17466            res.removedInfo.args = createInstallArgsForExisting(0,
17467                    deletedPackage.applicationInfo.getCodePath(),
17468                    deletedPackage.applicationInfo.getResourcePath(),
17469                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17470        } else {
17471            res.removedInfo.args = null;
17472        }
17473
17474        // Successfully disabled the old package. Now proceed with re-installation
17475        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17476                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17477        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17478
17479        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17480        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17481                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17482
17483        PackageParser.Package newPackage = null;
17484        try {
17485            // Add the package to the internal data structures
17486            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17487
17488            // Set the update and install times
17489            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17490            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17491                    System.currentTimeMillis());
17492
17493            // Update the package dynamic state if succeeded
17494            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17495                // Now that the install succeeded make sure we remove data
17496                // directories for any child package the update removed.
17497                final int deletedChildCount = (deletedPackage.childPackages != null)
17498                        ? deletedPackage.childPackages.size() : 0;
17499                final int newChildCount = (newPackage.childPackages != null)
17500                        ? newPackage.childPackages.size() : 0;
17501                for (int i = 0; i < deletedChildCount; i++) {
17502                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17503                    boolean childPackageDeleted = true;
17504                    for (int j = 0; j < newChildCount; j++) {
17505                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17506                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17507                            childPackageDeleted = false;
17508                            break;
17509                        }
17510                    }
17511                    if (childPackageDeleted) {
17512                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17513                                deletedChildPkg.packageName);
17514                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17515                            PackageRemovedInfo removedChildRes = res.removedInfo
17516                                    .removedChildPackages.get(deletedChildPkg.packageName);
17517                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17518                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17519                        }
17520                    }
17521                }
17522
17523                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17524                        installReason);
17525                prepareAppDataAfterInstallLIF(newPackage);
17526
17527                mDexManager.notifyPackageUpdated(newPackage.packageName,
17528                            newPackage.baseCodePath, newPackage.splitCodePaths);
17529            }
17530        } catch (PackageManagerException e) {
17531            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17532            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17533        }
17534
17535        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17536            // Re installation failed. Restore old information
17537            // Remove new pkg information
17538            if (newPackage != null) {
17539                removeInstalledPackageLI(newPackage, true);
17540            }
17541            // Add back the old system package
17542            try {
17543                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17544            } catch (PackageManagerException e) {
17545                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17546            }
17547
17548            synchronized (mPackages) {
17549                if (disabledSystem) {
17550                    enableSystemPackageLPw(deletedPackage);
17551                }
17552
17553                // Ensure the installer package name up to date
17554                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17555
17556                // Update permissions for restored package
17557                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17558
17559                mSettings.writeLPr();
17560            }
17561
17562            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17563                    + " after failed upgrade");
17564        }
17565    }
17566
17567    /**
17568     * Checks whether the parent or any of the child packages have a change shared
17569     * user. For a package to be a valid update the shred users of the parent and
17570     * the children should match. We may later support changing child shared users.
17571     * @param oldPkg The updated package.
17572     * @param newPkg The update package.
17573     * @return The shared user that change between the versions.
17574     */
17575    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17576            PackageParser.Package newPkg) {
17577        // Check parent shared user
17578        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17579            return newPkg.packageName;
17580        }
17581        // Check child shared users
17582        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17583        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17584        for (int i = 0; i < newChildCount; i++) {
17585            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17586            // If this child was present, did it have the same shared user?
17587            for (int j = 0; j < oldChildCount; j++) {
17588                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17589                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17590                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17591                    return newChildPkg.packageName;
17592                }
17593            }
17594        }
17595        return null;
17596    }
17597
17598    private void removeNativeBinariesLI(PackageSetting ps) {
17599        // Remove the lib path for the parent package
17600        if (ps != null) {
17601            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17602            // Remove the lib path for the child packages
17603            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17604            for (int i = 0; i < childCount; i++) {
17605                PackageSetting childPs = null;
17606                synchronized (mPackages) {
17607                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17608                }
17609                if (childPs != null) {
17610                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17611                            .legacyNativeLibraryPathString);
17612                }
17613            }
17614        }
17615    }
17616
17617    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17618        // Enable the parent package
17619        mSettings.enableSystemPackageLPw(pkg.packageName);
17620        // Enable the child packages
17621        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17622        for (int i = 0; i < childCount; i++) {
17623            PackageParser.Package childPkg = pkg.childPackages.get(i);
17624            mSettings.enableSystemPackageLPw(childPkg.packageName);
17625        }
17626    }
17627
17628    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17629            PackageParser.Package newPkg) {
17630        // Disable the parent package (parent always replaced)
17631        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17632        // Disable the child packages
17633        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17634        for (int i = 0; i < childCount; i++) {
17635            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17636            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17637            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17638        }
17639        return disabled;
17640    }
17641
17642    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17643            String installerPackageName) {
17644        // Enable the parent package
17645        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17646        // Enable the child packages
17647        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17648        for (int i = 0; i < childCount; i++) {
17649            PackageParser.Package childPkg = pkg.childPackages.get(i);
17650            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17651        }
17652    }
17653
17654    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17655        // Collect all used permissions in the UID
17656        ArraySet<String> usedPermissions = new ArraySet<>();
17657        final int packageCount = su.packages.size();
17658        for (int i = 0; i < packageCount; i++) {
17659            PackageSetting ps = su.packages.valueAt(i);
17660            if (ps.pkg == null) {
17661                continue;
17662            }
17663            final int requestedPermCount = ps.pkg.requestedPermissions.size();
17664            for (int j = 0; j < requestedPermCount; j++) {
17665                String permission = ps.pkg.requestedPermissions.get(j);
17666                BasePermission bp = mSettings.mPermissions.get(permission);
17667                if (bp != null) {
17668                    usedPermissions.add(permission);
17669                }
17670            }
17671        }
17672
17673        PermissionsState permissionsState = su.getPermissionsState();
17674        // Prune install permissions
17675        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17676        final int installPermCount = installPermStates.size();
17677        for (int i = installPermCount - 1; i >= 0;  i--) {
17678            PermissionState permissionState = installPermStates.get(i);
17679            if (!usedPermissions.contains(permissionState.getName())) {
17680                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17681                if (bp != null) {
17682                    permissionsState.revokeInstallPermission(bp);
17683                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
17684                            PackageManager.MASK_PERMISSION_FLAGS, 0);
17685                }
17686            }
17687        }
17688
17689        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
17690
17691        // Prune runtime permissions
17692        for (int userId : allUserIds) {
17693            List<PermissionState> runtimePermStates = permissionsState
17694                    .getRuntimePermissionStates(userId);
17695            final int runtimePermCount = runtimePermStates.size();
17696            for (int i = runtimePermCount - 1; i >= 0; i--) {
17697                PermissionState permissionState = runtimePermStates.get(i);
17698                if (!usedPermissions.contains(permissionState.getName())) {
17699                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17700                    if (bp != null) {
17701                        permissionsState.revokeRuntimePermission(bp, userId);
17702                        permissionsState.updatePermissionFlags(bp, userId,
17703                                PackageManager.MASK_PERMISSION_FLAGS, 0);
17704                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
17705                                runtimePermissionChangedUserIds, userId);
17706                    }
17707                }
17708            }
17709        }
17710
17711        return runtimePermissionChangedUserIds;
17712    }
17713
17714    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
17715            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
17716        // Update the parent package setting
17717        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
17718                res, user, installReason);
17719        // Update the child packages setting
17720        final int childCount = (newPackage.childPackages != null)
17721                ? newPackage.childPackages.size() : 0;
17722        for (int i = 0; i < childCount; i++) {
17723            PackageParser.Package childPackage = newPackage.childPackages.get(i);
17724            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
17725            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
17726                    childRes.origUsers, childRes, user, installReason);
17727        }
17728    }
17729
17730    private void updateSettingsInternalLI(PackageParser.Package newPackage,
17731            String installerPackageName, int[] allUsers, int[] installedForUsers,
17732            PackageInstalledInfo res, UserHandle user, int installReason) {
17733        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17734
17735        String pkgName = newPackage.packageName;
17736        synchronized (mPackages) {
17737            //write settings. the installStatus will be incomplete at this stage.
17738            //note that the new package setting would have already been
17739            //added to mPackages. It hasn't been persisted yet.
17740            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17741            // TODO: Remove this write? It's also written at the end of this method
17742            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17743            mSettings.writeLPr();
17744            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17745        }
17746
17747        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17748        synchronized (mPackages) {
17749            updatePermissionsLPw(newPackage.packageName, newPackage,
17750                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17751                            ? UPDATE_PERMISSIONS_ALL : 0));
17752            // For system-bundled packages, we assume that installing an upgraded version
17753            // of the package implies that the user actually wants to run that new code,
17754            // so we enable the package.
17755            PackageSetting ps = mSettings.mPackages.get(pkgName);
17756            final int userId = user.getIdentifier();
17757            if (ps != null) {
17758                if (isSystemApp(newPackage)) {
17759                    if (DEBUG_INSTALL) {
17760                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17761                    }
17762                    // Enable system package for requested users
17763                    if (res.origUsers != null) {
17764                        for (int origUserId : res.origUsers) {
17765                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
17766                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17767                                        origUserId, installerPackageName);
17768                            }
17769                        }
17770                    }
17771                    // Also convey the prior install/uninstall state
17772                    if (allUsers != null && installedForUsers != null) {
17773                        for (int currentUserId : allUsers) {
17774                            final boolean installed = ArrayUtils.contains(
17775                                    installedForUsers, currentUserId);
17776                            if (DEBUG_INSTALL) {
17777                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
17778                            }
17779                            ps.setInstalled(installed, currentUserId);
17780                        }
17781                        // these install state changes will be persisted in the
17782                        // upcoming call to mSettings.writeLPr().
17783                    }
17784                }
17785                // It's implied that when a user requests installation, they want the app to be
17786                // installed and enabled.
17787                if (userId != UserHandle.USER_ALL) {
17788                    ps.setInstalled(true, userId);
17789                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17790                }
17791
17792                // When replacing an existing package, preserve the original install reason for all
17793                // users that had the package installed before.
17794                final Set<Integer> previousUserIds = new ArraySet<>();
17795                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17796                    final int installReasonCount = res.removedInfo.installReasons.size();
17797                    for (int i = 0; i < installReasonCount; i++) {
17798                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17799                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17800                        ps.setInstallReason(previousInstallReason, previousUserId);
17801                        previousUserIds.add(previousUserId);
17802                    }
17803                }
17804
17805                // Set install reason for users that are having the package newly installed.
17806                if (userId == UserHandle.USER_ALL) {
17807                    for (int currentUserId : sUserManager.getUserIds()) {
17808                        if (!previousUserIds.contains(currentUserId)) {
17809                            ps.setInstallReason(installReason, currentUserId);
17810                        }
17811                    }
17812                } else if (!previousUserIds.contains(userId)) {
17813                    ps.setInstallReason(installReason, userId);
17814                }
17815                mSettings.writeKernelMappingLPr(ps);
17816            }
17817            res.name = pkgName;
17818            res.uid = newPackage.applicationInfo.uid;
17819            res.pkg = newPackage;
17820            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17821            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17822            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17823            //to update install status
17824            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17825            mSettings.writeLPr();
17826            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17827        }
17828
17829        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17830    }
17831
17832    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17833        try {
17834            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17835            installPackageLI(args, res);
17836        } finally {
17837            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17838        }
17839    }
17840
17841    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17842        final int installFlags = args.installFlags;
17843        final String installerPackageName = args.installerPackageName;
17844        final String volumeUuid = args.volumeUuid;
17845        final File tmpPackageFile = new File(args.getCodePath());
17846        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17847        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17848                || (args.volumeUuid != null));
17849        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17850        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17851        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17852        boolean replace = false;
17853        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17854        if (args.move != null) {
17855            // moving a complete application; perform an initial scan on the new install location
17856            scanFlags |= SCAN_INITIAL;
17857        }
17858        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17859            scanFlags |= SCAN_DONT_KILL_APP;
17860        }
17861        if (instantApp) {
17862            scanFlags |= SCAN_AS_INSTANT_APP;
17863        }
17864        if (fullApp) {
17865            scanFlags |= SCAN_AS_FULL_APP;
17866        }
17867
17868        // Result object to be returned
17869        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17870
17871        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17872
17873        // Sanity check
17874        if (instantApp && (forwardLocked || onExternal)) {
17875            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17876                    + " external=" + onExternal);
17877            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17878            return;
17879        }
17880
17881        // Retrieve PackageSettings and parse package
17882        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17883                | PackageParser.PARSE_ENFORCE_CODE
17884                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17885                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17886                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17887                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17888        PackageParser pp = new PackageParser();
17889        pp.setSeparateProcesses(mSeparateProcesses);
17890        pp.setDisplayMetrics(mMetrics);
17891        pp.setCallback(mPackageParserCallback);
17892
17893        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17894        final PackageParser.Package pkg;
17895        try {
17896            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17897        } catch (PackageParserException e) {
17898            res.setError("Failed parse during installPackageLI", e);
17899            return;
17900        } finally {
17901            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17902        }
17903
17904        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17905        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17906            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
17907            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17908                    "Instant app package must target O");
17909            return;
17910        }
17911        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17912            Slog.w(TAG, "Instant app package " + pkg.packageName
17913                    + " does not target targetSandboxVersion 2");
17914            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17915                    "Instant app package must use targetSanboxVersion 2");
17916            return;
17917        }
17918
17919        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17920            // Static shared libraries have synthetic package names
17921            renameStaticSharedLibraryPackage(pkg);
17922
17923            // No static shared libs on external storage
17924            if (onExternal) {
17925                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17926                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17927                        "Packages declaring static-shared libs cannot be updated");
17928                return;
17929            }
17930        }
17931
17932        // If we are installing a clustered package add results for the children
17933        if (pkg.childPackages != null) {
17934            synchronized (mPackages) {
17935                final int childCount = pkg.childPackages.size();
17936                for (int i = 0; i < childCount; i++) {
17937                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17938                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17939                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17940                    childRes.pkg = childPkg;
17941                    childRes.name = childPkg.packageName;
17942                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17943                    if (childPs != null) {
17944                        childRes.origUsers = childPs.queryInstalledUsers(
17945                                sUserManager.getUserIds(), true);
17946                    }
17947                    if ((mPackages.containsKey(childPkg.packageName))) {
17948                        childRes.removedInfo = new PackageRemovedInfo(this);
17949                        childRes.removedInfo.removedPackage = childPkg.packageName;
17950                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17951                    }
17952                    if (res.addedChildPackages == null) {
17953                        res.addedChildPackages = new ArrayMap<>();
17954                    }
17955                    res.addedChildPackages.put(childPkg.packageName, childRes);
17956                }
17957            }
17958        }
17959
17960        // If package doesn't declare API override, mark that we have an install
17961        // time CPU ABI override.
17962        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17963            pkg.cpuAbiOverride = args.abiOverride;
17964        }
17965
17966        String pkgName = res.name = pkg.packageName;
17967        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17968            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17969                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17970                return;
17971            }
17972        }
17973
17974        try {
17975            // either use what we've been given or parse directly from the APK
17976            if (args.certificates != null) {
17977                try {
17978                    PackageParser.populateCertificates(pkg, args.certificates);
17979                } catch (PackageParserException e) {
17980                    // there was something wrong with the certificates we were given;
17981                    // try to pull them from the APK
17982                    PackageParser.collectCertificates(pkg, parseFlags);
17983                }
17984            } else {
17985                PackageParser.collectCertificates(pkg, parseFlags);
17986            }
17987        } catch (PackageParserException e) {
17988            res.setError("Failed collect during installPackageLI", e);
17989            return;
17990        }
17991
17992        // Get rid of all references to package scan path via parser.
17993        pp = null;
17994        String oldCodePath = null;
17995        boolean systemApp = false;
17996        synchronized (mPackages) {
17997            // Check if installing already existing package
17998            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17999                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18000                if (pkg.mOriginalPackages != null
18001                        && pkg.mOriginalPackages.contains(oldName)
18002                        && mPackages.containsKey(oldName)) {
18003                    // This package is derived from an original package,
18004                    // and this device has been updating from that original
18005                    // name.  We must continue using the original name, so
18006                    // rename the new package here.
18007                    pkg.setPackageName(oldName);
18008                    pkgName = pkg.packageName;
18009                    replace = true;
18010                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18011                            + oldName + " pkgName=" + pkgName);
18012                } else if (mPackages.containsKey(pkgName)) {
18013                    // This package, under its official name, already exists
18014                    // on the device; we should replace it.
18015                    replace = true;
18016                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18017                }
18018
18019                // Child packages are installed through the parent package
18020                if (pkg.parentPackage != null) {
18021                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18022                            "Package " + pkg.packageName + " is child of package "
18023                                    + pkg.parentPackage.parentPackage + ". Child packages "
18024                                    + "can be updated only through the parent package.");
18025                    return;
18026                }
18027
18028                if (replace) {
18029                    // Prevent apps opting out from runtime permissions
18030                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18031                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18032                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18033                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18034                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18035                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18036                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18037                                        + " doesn't support runtime permissions but the old"
18038                                        + " target SDK " + oldTargetSdk + " does.");
18039                        return;
18040                    }
18041                    // Prevent apps from downgrading their targetSandbox.
18042                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18043                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18044                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18045                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18046                                "Package " + pkg.packageName + " new target sandbox "
18047                                + newTargetSandbox + " is incompatible with the previous value of"
18048                                + oldTargetSandbox + ".");
18049                        return;
18050                    }
18051
18052                    // Prevent installing of child packages
18053                    if (oldPackage.parentPackage != null) {
18054                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18055                                "Package " + pkg.packageName + " is child of package "
18056                                        + oldPackage.parentPackage + ". Child packages "
18057                                        + "can be updated only through the parent package.");
18058                        return;
18059                    }
18060                }
18061            }
18062
18063            PackageSetting ps = mSettings.mPackages.get(pkgName);
18064            if (ps != null) {
18065                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18066
18067                // Static shared libs have same package with different versions where
18068                // we internally use a synthetic package name to allow multiple versions
18069                // of the same package, therefore we need to compare signatures against
18070                // the package setting for the latest library version.
18071                PackageSetting signatureCheckPs = ps;
18072                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18073                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18074                    if (libraryEntry != null) {
18075                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18076                    }
18077                }
18078
18079                // Quick sanity check that we're signed correctly if updating;
18080                // we'll check this again later when scanning, but we want to
18081                // bail early here before tripping over redefined permissions.
18082                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18083                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18084                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18085                                + pkg.packageName + " upgrade keys do not match the "
18086                                + "previously installed version");
18087                        return;
18088                    }
18089                } else {
18090                    try {
18091                        verifySignaturesLP(signatureCheckPs, pkg);
18092                    } catch (PackageManagerException e) {
18093                        res.setError(e.error, e.getMessage());
18094                        return;
18095                    }
18096                }
18097
18098                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18099                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18100                    systemApp = (ps.pkg.applicationInfo.flags &
18101                            ApplicationInfo.FLAG_SYSTEM) != 0;
18102                }
18103                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18104            }
18105
18106            int N = pkg.permissions.size();
18107            for (int i = N-1; i >= 0; i--) {
18108                PackageParser.Permission perm = pkg.permissions.get(i);
18109                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18110
18111                // Don't allow anyone but the system to define ephemeral permissions.
18112                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
18113                        && !systemApp) {
18114                    Slog.w(TAG, "Non-System package " + pkg.packageName
18115                            + " attempting to delcare ephemeral permission "
18116                            + perm.info.name + "; Removing ephemeral.");
18117                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
18118                }
18119                // Check whether the newly-scanned package wants to define an already-defined perm
18120                if (bp != null) {
18121                    // If the defining package is signed with our cert, it's okay.  This
18122                    // also includes the "updating the same package" case, of course.
18123                    // "updating same package" could also involve key-rotation.
18124                    final boolean sigsOk;
18125                    if (bp.sourcePackage.equals(pkg.packageName)
18126                            && (bp.packageSetting instanceof PackageSetting)
18127                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18128                                    scanFlags))) {
18129                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18130                    } else {
18131                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18132                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18133                    }
18134                    if (!sigsOk) {
18135                        // If the owning package is the system itself, we log but allow
18136                        // install to proceed; we fail the install on all other permission
18137                        // redefinitions.
18138                        if (!bp.sourcePackage.equals("android")) {
18139                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18140                                    + pkg.packageName + " attempting to redeclare permission "
18141                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18142                            res.origPermission = perm.info.name;
18143                            res.origPackage = bp.sourcePackage;
18144                            return;
18145                        } else {
18146                            Slog.w(TAG, "Package " + pkg.packageName
18147                                    + " attempting to redeclare system permission "
18148                                    + perm.info.name + "; ignoring new declaration");
18149                            pkg.permissions.remove(i);
18150                        }
18151                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18152                        // Prevent apps to change protection level to dangerous from any other
18153                        // type as this would allow a privilege escalation where an app adds a
18154                        // normal/signature permission in other app's group and later redefines
18155                        // it as dangerous leading to the group auto-grant.
18156                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18157                                == PermissionInfo.PROTECTION_DANGEROUS) {
18158                            if (bp != null && !bp.isRuntime()) {
18159                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18160                                        + "non-runtime permission " + perm.info.name
18161                                        + " to runtime; keeping old protection level");
18162                                perm.info.protectionLevel = bp.protectionLevel;
18163                            }
18164                        }
18165                    }
18166                }
18167            }
18168        }
18169
18170        if (systemApp) {
18171            if (onExternal) {
18172                // Abort update; system app can't be replaced with app on sdcard
18173                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18174                        "Cannot install updates to system apps on sdcard");
18175                return;
18176            } else if (instantApp) {
18177                // Abort update; system app can't be replaced with an instant app
18178                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18179                        "Cannot update a system app with an instant app");
18180                return;
18181            }
18182        }
18183
18184        if (args.move != null) {
18185            // We did an in-place move, so dex is ready to roll
18186            scanFlags |= SCAN_NO_DEX;
18187            scanFlags |= SCAN_MOVE;
18188
18189            synchronized (mPackages) {
18190                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18191                if (ps == null) {
18192                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18193                            "Missing settings for moved package " + pkgName);
18194                }
18195
18196                // We moved the entire application as-is, so bring over the
18197                // previously derived ABI information.
18198                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18199                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18200            }
18201
18202        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18203            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18204            scanFlags |= SCAN_NO_DEX;
18205
18206            try {
18207                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18208                    args.abiOverride : pkg.cpuAbiOverride);
18209                final boolean extractNativeLibs = !pkg.isLibrary();
18210                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18211                        extractNativeLibs, mAppLib32InstallDir);
18212            } catch (PackageManagerException pme) {
18213                Slog.e(TAG, "Error deriving application ABI", pme);
18214                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18215                return;
18216            }
18217
18218            // Shared libraries for the package need to be updated.
18219            synchronized (mPackages) {
18220                try {
18221                    updateSharedLibrariesLPr(pkg, null);
18222                } catch (PackageManagerException e) {
18223                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18224                }
18225            }
18226
18227            // dexopt can take some time to complete, so, for instant apps, we skip this
18228            // step during installation. Instead, we'll take extra time the first time the
18229            // instant app starts. It's preferred to do it this way to provide continuous
18230            // progress to the user instead of mysteriously blocking somewhere in the
18231            // middle of running an instant app. The default behaviour can be overridden
18232            // via gservices.
18233            if (!instantApp || Global.getInt(
18234                        mContext.getContentResolver(), Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0) {
18235                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18236                // Do not run PackageDexOptimizer through the local performDexOpt
18237                // method because `pkg` may not be in `mPackages` yet.
18238                //
18239                // Also, don't fail application installs if the dexopt step fails.
18240                DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
18241                        REASON_INSTALL,
18242                        DexoptOptions.DEXOPT_BOOT_COMPLETE);
18243                mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18244                        null /* instructionSets */,
18245                        getOrCreateCompilerPackageStats(pkg),
18246                        mDexManager.isUsedByOtherApps(pkg.packageName),
18247                        dexoptOptions);
18248                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18249            }
18250
18251            // Notify BackgroundDexOptService that the package has been changed.
18252            // If this is an update of a package which used to fail to compile,
18253            // BDOS will remove it from its blacklist.
18254            // TODO: Layering violation
18255            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18256        }
18257
18258        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18259            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18260            return;
18261        }
18262
18263        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18264
18265        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18266                "installPackageLI")) {
18267            if (replace) {
18268                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18269                    // Static libs have a synthetic package name containing the version
18270                    // and cannot be updated as an update would get a new package name,
18271                    // unless this is the exact same version code which is useful for
18272                    // development.
18273                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18274                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18275                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18276                                + "static-shared libs cannot be updated");
18277                        return;
18278                    }
18279                }
18280                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18281                        installerPackageName, res, args.installReason);
18282            } else {
18283                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18284                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18285            }
18286        }
18287
18288        synchronized (mPackages) {
18289            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18290            if (ps != null) {
18291                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18292                ps.setUpdateAvailable(false /*updateAvailable*/);
18293            }
18294
18295            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18296            for (int i = 0; i < childCount; i++) {
18297                PackageParser.Package childPkg = pkg.childPackages.get(i);
18298                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18299                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18300                if (childPs != null) {
18301                    childRes.newUsers = childPs.queryInstalledUsers(
18302                            sUserManager.getUserIds(), true);
18303                }
18304            }
18305
18306            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18307                updateSequenceNumberLP(ps, res.newUsers);
18308                updateInstantAppInstallerLocked(pkgName);
18309            }
18310        }
18311    }
18312
18313    private void startIntentFilterVerifications(int userId, boolean replacing,
18314            PackageParser.Package pkg) {
18315        if (mIntentFilterVerifierComponent == null) {
18316            Slog.w(TAG, "No IntentFilter verification will not be done as "
18317                    + "there is no IntentFilterVerifier available!");
18318            return;
18319        }
18320
18321        final int verifierUid = getPackageUid(
18322                mIntentFilterVerifierComponent.getPackageName(),
18323                MATCH_DEBUG_TRIAGED_MISSING,
18324                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18325
18326        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18327        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18328        mHandler.sendMessage(msg);
18329
18330        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18331        for (int i = 0; i < childCount; i++) {
18332            PackageParser.Package childPkg = pkg.childPackages.get(i);
18333            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18334            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18335            mHandler.sendMessage(msg);
18336        }
18337    }
18338
18339    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18340            PackageParser.Package pkg) {
18341        int size = pkg.activities.size();
18342        if (size == 0) {
18343            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18344                    "No activity, so no need to verify any IntentFilter!");
18345            return;
18346        }
18347
18348        final boolean hasDomainURLs = hasDomainURLs(pkg);
18349        if (!hasDomainURLs) {
18350            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18351                    "No domain URLs, so no need to verify any IntentFilter!");
18352            return;
18353        }
18354
18355        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18356                + " if any IntentFilter from the " + size
18357                + " Activities needs verification ...");
18358
18359        int count = 0;
18360        final String packageName = pkg.packageName;
18361
18362        synchronized (mPackages) {
18363            // If this is a new install and we see that we've already run verification for this
18364            // package, we have nothing to do: it means the state was restored from backup.
18365            if (!replacing) {
18366                IntentFilterVerificationInfo ivi =
18367                        mSettings.getIntentFilterVerificationLPr(packageName);
18368                if (ivi != null) {
18369                    if (DEBUG_DOMAIN_VERIFICATION) {
18370                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18371                                + ivi.getStatusString());
18372                    }
18373                    return;
18374                }
18375            }
18376
18377            // If any filters need to be verified, then all need to be.
18378            boolean needToVerify = false;
18379            for (PackageParser.Activity a : pkg.activities) {
18380                for (ActivityIntentInfo filter : a.intents) {
18381                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18382                        if (DEBUG_DOMAIN_VERIFICATION) {
18383                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18384                        }
18385                        needToVerify = true;
18386                        break;
18387                    }
18388                }
18389            }
18390
18391            if (needToVerify) {
18392                final int verificationId = mIntentFilterVerificationToken++;
18393                for (PackageParser.Activity a : pkg.activities) {
18394                    for (ActivityIntentInfo filter : a.intents) {
18395                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18396                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18397                                    "Verification needed for IntentFilter:" + filter.toString());
18398                            mIntentFilterVerifier.addOneIntentFilterVerification(
18399                                    verifierUid, userId, verificationId, filter, packageName);
18400                            count++;
18401                        }
18402                    }
18403                }
18404            }
18405        }
18406
18407        if (count > 0) {
18408            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18409                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18410                    +  " for userId:" + userId);
18411            mIntentFilterVerifier.startVerifications(userId);
18412        } else {
18413            if (DEBUG_DOMAIN_VERIFICATION) {
18414                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18415            }
18416        }
18417    }
18418
18419    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18420        final ComponentName cn  = filter.activity.getComponentName();
18421        final String packageName = cn.getPackageName();
18422
18423        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18424                packageName);
18425        if (ivi == null) {
18426            return true;
18427        }
18428        int status = ivi.getStatus();
18429        switch (status) {
18430            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18431            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18432                return true;
18433
18434            default:
18435                // Nothing to do
18436                return false;
18437        }
18438    }
18439
18440    private static boolean isMultiArch(ApplicationInfo info) {
18441        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18442    }
18443
18444    private static boolean isExternal(PackageParser.Package pkg) {
18445        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18446    }
18447
18448    private static boolean isExternal(PackageSetting ps) {
18449        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18450    }
18451
18452    private static boolean isSystemApp(PackageParser.Package pkg) {
18453        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18454    }
18455
18456    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18457        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18458    }
18459
18460    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18461        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18462    }
18463
18464    private static boolean isSystemApp(PackageSetting ps) {
18465        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18466    }
18467
18468    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18469        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18470    }
18471
18472    private int packageFlagsToInstallFlags(PackageSetting ps) {
18473        int installFlags = 0;
18474        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18475            // This existing package was an external ASEC install when we have
18476            // the external flag without a UUID
18477            installFlags |= PackageManager.INSTALL_EXTERNAL;
18478        }
18479        if (ps.isForwardLocked()) {
18480            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18481        }
18482        return installFlags;
18483    }
18484
18485    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18486        if (isExternal(pkg)) {
18487            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18488                return StorageManager.UUID_PRIMARY_PHYSICAL;
18489            } else {
18490                return pkg.volumeUuid;
18491            }
18492        } else {
18493            return StorageManager.UUID_PRIVATE_INTERNAL;
18494        }
18495    }
18496
18497    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18498        if (isExternal(pkg)) {
18499            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18500                return mSettings.getExternalVersion();
18501            } else {
18502                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18503            }
18504        } else {
18505            return mSettings.getInternalVersion();
18506        }
18507    }
18508
18509    private void deleteTempPackageFiles() {
18510        final FilenameFilter filter = new FilenameFilter() {
18511            public boolean accept(File dir, String name) {
18512                return name.startsWith("vmdl") && name.endsWith(".tmp");
18513            }
18514        };
18515        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18516            file.delete();
18517        }
18518    }
18519
18520    @Override
18521    public void deletePackageAsUser(String packageName, int versionCode,
18522            IPackageDeleteObserver observer, int userId, int flags) {
18523        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18524                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18525    }
18526
18527    @Override
18528    public void deletePackageVersioned(VersionedPackage versionedPackage,
18529            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18530        final int callingUid = Binder.getCallingUid();
18531        mContext.enforceCallingOrSelfPermission(
18532                android.Manifest.permission.DELETE_PACKAGES, null);
18533        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18534        Preconditions.checkNotNull(versionedPackage);
18535        Preconditions.checkNotNull(observer);
18536        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18537                PackageManager.VERSION_CODE_HIGHEST,
18538                Integer.MAX_VALUE, "versionCode must be >= -1");
18539
18540        final String packageName = versionedPackage.getPackageName();
18541        final int versionCode = versionedPackage.getVersionCode();
18542        final String internalPackageName;
18543        synchronized (mPackages) {
18544            // Normalize package name to handle renamed packages and static libs
18545            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18546                    versionedPackage.getVersionCode());
18547        }
18548
18549        final int uid = Binder.getCallingUid();
18550        if (!isOrphaned(internalPackageName)
18551                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18552            try {
18553                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18554                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18555                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18556                observer.onUserActionRequired(intent);
18557            } catch (RemoteException re) {
18558            }
18559            return;
18560        }
18561        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18562        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18563        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18564            mContext.enforceCallingOrSelfPermission(
18565                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18566                    "deletePackage for user " + userId);
18567        }
18568
18569        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18570            try {
18571                observer.onPackageDeleted(packageName,
18572                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18573            } catch (RemoteException re) {
18574            }
18575            return;
18576        }
18577
18578        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18579            try {
18580                observer.onPackageDeleted(packageName,
18581                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18582            } catch (RemoteException re) {
18583            }
18584            return;
18585        }
18586
18587        if (DEBUG_REMOVE) {
18588            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18589                    + " deleteAllUsers: " + deleteAllUsers + " version="
18590                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18591                    ? "VERSION_CODE_HIGHEST" : versionCode));
18592        }
18593        // Queue up an async operation since the package deletion may take a little while.
18594        mHandler.post(new Runnable() {
18595            public void run() {
18596                mHandler.removeCallbacks(this);
18597                int returnCode;
18598                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18599                boolean doDeletePackage = true;
18600                if (ps != null) {
18601                    final boolean targetIsInstantApp =
18602                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18603                    doDeletePackage = !targetIsInstantApp
18604                            || canViewInstantApps;
18605                }
18606                if (doDeletePackage) {
18607                    if (!deleteAllUsers) {
18608                        returnCode = deletePackageX(internalPackageName, versionCode,
18609                                userId, deleteFlags);
18610                    } else {
18611                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
18612                                internalPackageName, users);
18613                        // If nobody is blocking uninstall, proceed with delete for all users
18614                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18615                            returnCode = deletePackageX(internalPackageName, versionCode,
18616                                    userId, deleteFlags);
18617                        } else {
18618                            // Otherwise uninstall individually for users with blockUninstalls=false
18619                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18620                            for (int userId : users) {
18621                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18622                                    returnCode = deletePackageX(internalPackageName, versionCode,
18623                                            userId, userFlags);
18624                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18625                                        Slog.w(TAG, "Package delete failed for user " + userId
18626                                                + ", returnCode " + returnCode);
18627                                    }
18628                                }
18629                            }
18630                            // The app has only been marked uninstalled for certain users.
18631                            // We still need to report that delete was blocked
18632                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18633                        }
18634                    }
18635                } else {
18636                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18637                }
18638                try {
18639                    observer.onPackageDeleted(packageName, returnCode, null);
18640                } catch (RemoteException e) {
18641                    Log.i(TAG, "Observer no longer exists.");
18642                } //end catch
18643            } //end run
18644        });
18645    }
18646
18647    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18648        if (pkg.staticSharedLibName != null) {
18649            return pkg.manifestPackageName;
18650        }
18651        return pkg.packageName;
18652    }
18653
18654    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18655        // Handle renamed packages
18656        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18657        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18658
18659        // Is this a static library?
18660        SparseArray<SharedLibraryEntry> versionedLib =
18661                mStaticLibsByDeclaringPackage.get(packageName);
18662        if (versionedLib == null || versionedLib.size() <= 0) {
18663            return packageName;
18664        }
18665
18666        // Figure out which lib versions the caller can see
18667        SparseIntArray versionsCallerCanSee = null;
18668        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18669        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18670                && callingAppId != Process.ROOT_UID) {
18671            versionsCallerCanSee = new SparseIntArray();
18672            String libName = versionedLib.valueAt(0).info.getName();
18673            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18674            if (uidPackages != null) {
18675                for (String uidPackage : uidPackages) {
18676                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18677                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18678                    if (libIdx >= 0) {
18679                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18680                        versionsCallerCanSee.append(libVersion, libVersion);
18681                    }
18682                }
18683            }
18684        }
18685
18686        // Caller can see nothing - done
18687        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18688            return packageName;
18689        }
18690
18691        // Find the version the caller can see and the app version code
18692        SharedLibraryEntry highestVersion = null;
18693        final int versionCount = versionedLib.size();
18694        for (int i = 0; i < versionCount; i++) {
18695            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18696            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18697                    libEntry.info.getVersion()) < 0) {
18698                continue;
18699            }
18700            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18701            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18702                if (libVersionCode == versionCode) {
18703                    return libEntry.apk;
18704                }
18705            } else if (highestVersion == null) {
18706                highestVersion = libEntry;
18707            } else if (libVersionCode  > highestVersion.info
18708                    .getDeclaringPackage().getVersionCode()) {
18709                highestVersion = libEntry;
18710            }
18711        }
18712
18713        if (highestVersion != null) {
18714            return highestVersion.apk;
18715        }
18716
18717        return packageName;
18718    }
18719
18720    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18721        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18722              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18723            return true;
18724        }
18725        final int callingUserId = UserHandle.getUserId(callingUid);
18726        // If the caller installed the pkgName, then allow it to silently uninstall.
18727        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18728            return true;
18729        }
18730
18731        // Allow package verifier to silently uninstall.
18732        if (mRequiredVerifierPackage != null &&
18733                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18734            return true;
18735        }
18736
18737        // Allow package uninstaller to silently uninstall.
18738        if (mRequiredUninstallerPackage != null &&
18739                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18740            return true;
18741        }
18742
18743        // Allow storage manager to silently uninstall.
18744        if (mStorageManagerPackage != null &&
18745                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18746            return true;
18747        }
18748
18749        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
18750        // uninstall for device owner provisioning.
18751        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
18752                == PERMISSION_GRANTED) {
18753            return true;
18754        }
18755
18756        return false;
18757    }
18758
18759    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18760        int[] result = EMPTY_INT_ARRAY;
18761        for (int userId : userIds) {
18762            if (getBlockUninstallForUser(packageName, userId)) {
18763                result = ArrayUtils.appendInt(result, userId);
18764            }
18765        }
18766        return result;
18767    }
18768
18769    @Override
18770    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18771        final int callingUid = Binder.getCallingUid();
18772        if (getInstantAppPackageName(callingUid) != null
18773                && !isCallerSameApp(packageName, callingUid)) {
18774            return false;
18775        }
18776        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18777    }
18778
18779    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18780        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18781                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18782        try {
18783            if (dpm != null) {
18784                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18785                        /* callingUserOnly =*/ false);
18786                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18787                        : deviceOwnerComponentName.getPackageName();
18788                // Does the package contains the device owner?
18789                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18790                // this check is probably not needed, since DO should be registered as a device
18791                // admin on some user too. (Original bug for this: b/17657954)
18792                if (packageName.equals(deviceOwnerPackageName)) {
18793                    return true;
18794                }
18795                // Does it contain a device admin for any user?
18796                int[] users;
18797                if (userId == UserHandle.USER_ALL) {
18798                    users = sUserManager.getUserIds();
18799                } else {
18800                    users = new int[]{userId};
18801                }
18802                for (int i = 0; i < users.length; ++i) {
18803                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18804                        return true;
18805                    }
18806                }
18807            }
18808        } catch (RemoteException e) {
18809        }
18810        return false;
18811    }
18812
18813    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18814        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18815    }
18816
18817    /**
18818     *  This method is an internal method that could be get invoked either
18819     *  to delete an installed package or to clean up a failed installation.
18820     *  After deleting an installed package, a broadcast is sent to notify any
18821     *  listeners that the package has been removed. For cleaning up a failed
18822     *  installation, the broadcast is not necessary since the package's
18823     *  installation wouldn't have sent the initial broadcast either
18824     *  The key steps in deleting a package are
18825     *  deleting the package information in internal structures like mPackages,
18826     *  deleting the packages base directories through installd
18827     *  updating mSettings to reflect current status
18828     *  persisting settings for later use
18829     *  sending a broadcast if necessary
18830     */
18831    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18832        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18833        final boolean res;
18834
18835        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18836                ? UserHandle.USER_ALL : userId;
18837
18838        if (isPackageDeviceAdmin(packageName, removeUser)) {
18839            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18840            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18841        }
18842
18843        PackageSetting uninstalledPs = null;
18844        PackageParser.Package pkg = null;
18845
18846        // for the uninstall-updates case and restricted profiles, remember the per-
18847        // user handle installed state
18848        int[] allUsers;
18849        synchronized (mPackages) {
18850            uninstalledPs = mSettings.mPackages.get(packageName);
18851            if (uninstalledPs == null) {
18852                Slog.w(TAG, "Not removing non-existent package " + packageName);
18853                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18854            }
18855
18856            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18857                    && uninstalledPs.versionCode != versionCode) {
18858                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18859                        + uninstalledPs.versionCode + " != " + versionCode);
18860                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18861            }
18862
18863            // Static shared libs can be declared by any package, so let us not
18864            // allow removing a package if it provides a lib others depend on.
18865            pkg = mPackages.get(packageName);
18866
18867            allUsers = sUserManager.getUserIds();
18868
18869            if (pkg != null && pkg.staticSharedLibName != null) {
18870                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18871                        pkg.staticSharedLibVersion);
18872                if (libEntry != null) {
18873                    for (int currUserId : allUsers) {
18874                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18875                            continue;
18876                        }
18877                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18878                                libEntry.info, 0, currUserId);
18879                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18880                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18881                                    + " hosting lib " + libEntry.info.getName() + " version "
18882                                    + libEntry.info.getVersion() + " used by " + libClientPackages
18883                                    + " for user " + currUserId);
18884                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18885                        }
18886                    }
18887                }
18888            }
18889
18890            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18891        }
18892
18893        final int freezeUser;
18894        if (isUpdatedSystemApp(uninstalledPs)
18895                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18896            // We're downgrading a system app, which will apply to all users, so
18897            // freeze them all during the downgrade
18898            freezeUser = UserHandle.USER_ALL;
18899        } else {
18900            freezeUser = removeUser;
18901        }
18902
18903        synchronized (mInstallLock) {
18904            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18905            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18906                    deleteFlags, "deletePackageX")) {
18907                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18908                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18909            }
18910            synchronized (mPackages) {
18911                if (res) {
18912                    if (pkg != null) {
18913                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18914                    }
18915                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18916                    updateInstantAppInstallerLocked(packageName);
18917                }
18918            }
18919        }
18920
18921        if (res) {
18922            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18923            info.sendPackageRemovedBroadcasts(killApp);
18924            info.sendSystemPackageUpdatedBroadcasts();
18925            info.sendSystemPackageAppearedBroadcasts();
18926        }
18927        // Force a gc here.
18928        Runtime.getRuntime().gc();
18929        // Delete the resources here after sending the broadcast to let
18930        // other processes clean up before deleting resources.
18931        if (info.args != null) {
18932            synchronized (mInstallLock) {
18933                info.args.doPostDeleteLI(true);
18934            }
18935        }
18936
18937        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18938    }
18939
18940    static class PackageRemovedInfo {
18941        final PackageSender packageSender;
18942        String removedPackage;
18943        String installerPackageName;
18944        int uid = -1;
18945        int removedAppId = -1;
18946        int[] origUsers;
18947        int[] removedUsers = null;
18948        int[] broadcastUsers = null;
18949        SparseArray<Integer> installReasons;
18950        boolean isRemovedPackageSystemUpdate = false;
18951        boolean isUpdate;
18952        boolean dataRemoved;
18953        boolean removedForAllUsers;
18954        boolean isStaticSharedLib;
18955        // Clean up resources deleted packages.
18956        InstallArgs args = null;
18957        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18958        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18959
18960        PackageRemovedInfo(PackageSender packageSender) {
18961            this.packageSender = packageSender;
18962        }
18963
18964        void sendPackageRemovedBroadcasts(boolean killApp) {
18965            sendPackageRemovedBroadcastInternal(killApp);
18966            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18967            for (int i = 0; i < childCount; i++) {
18968                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18969                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18970            }
18971        }
18972
18973        void sendSystemPackageUpdatedBroadcasts() {
18974            if (isRemovedPackageSystemUpdate) {
18975                sendSystemPackageUpdatedBroadcastsInternal();
18976                final int childCount = (removedChildPackages != null)
18977                        ? removedChildPackages.size() : 0;
18978                for (int i = 0; i < childCount; i++) {
18979                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18980                    if (childInfo.isRemovedPackageSystemUpdate) {
18981                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18982                    }
18983                }
18984            }
18985        }
18986
18987        void sendSystemPackageAppearedBroadcasts() {
18988            final int packageCount = (appearedChildPackages != null)
18989                    ? appearedChildPackages.size() : 0;
18990            for (int i = 0; i < packageCount; i++) {
18991                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18992                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18993                    true, UserHandle.getAppId(installedInfo.uid),
18994                    installedInfo.newUsers);
18995            }
18996        }
18997
18998        private void sendSystemPackageUpdatedBroadcastsInternal() {
18999            Bundle extras = new Bundle(2);
19000            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19001            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19002            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19003                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19004            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19005                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19006            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19007                null, null, 0, removedPackage, null, null);
19008            if (installerPackageName != null) {
19009                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19010                        removedPackage, extras, 0 /*flags*/,
19011                        installerPackageName, null, null);
19012                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19013                        removedPackage, extras, 0 /*flags*/,
19014                        installerPackageName, null, null);
19015            }
19016        }
19017
19018        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19019            // Don't send static shared library removal broadcasts as these
19020            // libs are visible only the the apps that depend on them an one
19021            // cannot remove the library if it has a dependency.
19022            if (isStaticSharedLib) {
19023                return;
19024            }
19025            Bundle extras = new Bundle(2);
19026            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19027            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19028            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19029            if (isUpdate || isRemovedPackageSystemUpdate) {
19030                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19031            }
19032            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19033            if (removedPackage != null) {
19034                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19035                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19036                if (installerPackageName != null) {
19037                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19038                            removedPackage, extras, 0 /*flags*/,
19039                            installerPackageName, null, broadcastUsers);
19040                }
19041                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19042                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19043                        removedPackage, extras,
19044                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19045                        null, null, broadcastUsers);
19046                }
19047            }
19048            if (removedAppId >= 0) {
19049                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19050                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19051                    null, null, broadcastUsers);
19052            }
19053        }
19054
19055        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19056            removedUsers = userIds;
19057            if (removedUsers == null) {
19058                broadcastUsers = null;
19059                return;
19060            }
19061
19062            broadcastUsers = EMPTY_INT_ARRAY;
19063            for (int i = userIds.length - 1; i >= 0; --i) {
19064                final int userId = userIds[i];
19065                if (deletedPackageSetting.getInstantApp(userId)) {
19066                    continue;
19067                }
19068                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19069            }
19070        }
19071    }
19072
19073    /*
19074     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19075     * flag is not set, the data directory is removed as well.
19076     * make sure this flag is set for partially installed apps. If not its meaningless to
19077     * delete a partially installed application.
19078     */
19079    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19080            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19081        String packageName = ps.name;
19082        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19083        // Retrieve object to delete permissions for shared user later on
19084        final PackageParser.Package deletedPkg;
19085        final PackageSetting deletedPs;
19086        // reader
19087        synchronized (mPackages) {
19088            deletedPkg = mPackages.get(packageName);
19089            deletedPs = mSettings.mPackages.get(packageName);
19090            if (outInfo != null) {
19091                outInfo.removedPackage = packageName;
19092                outInfo.installerPackageName = ps.installerPackageName;
19093                outInfo.isStaticSharedLib = deletedPkg != null
19094                        && deletedPkg.staticSharedLibName != null;
19095                outInfo.populateUsers(deletedPs == null ? null
19096                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19097            }
19098        }
19099
19100        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19101
19102        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19103            final PackageParser.Package resolvedPkg;
19104            if (deletedPkg != null) {
19105                resolvedPkg = deletedPkg;
19106            } else {
19107                // We don't have a parsed package when it lives on an ejected
19108                // adopted storage device, so fake something together
19109                resolvedPkg = new PackageParser.Package(ps.name);
19110                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19111            }
19112            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19113                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19114            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19115            if (outInfo != null) {
19116                outInfo.dataRemoved = true;
19117            }
19118            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19119        }
19120
19121        int removedAppId = -1;
19122
19123        // writer
19124        synchronized (mPackages) {
19125            boolean installedStateChanged = false;
19126            if (deletedPs != null) {
19127                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19128                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19129                    clearDefaultBrowserIfNeeded(packageName);
19130                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19131                    removedAppId = mSettings.removePackageLPw(packageName);
19132                    if (outInfo != null) {
19133                        outInfo.removedAppId = removedAppId;
19134                    }
19135                    updatePermissionsLPw(deletedPs.name, null, 0);
19136                    if (deletedPs.sharedUser != null) {
19137                        // Remove permissions associated with package. Since runtime
19138                        // permissions are per user we have to kill the removed package
19139                        // or packages running under the shared user of the removed
19140                        // package if revoking the permissions requested only by the removed
19141                        // package is successful and this causes a change in gids.
19142                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19143                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19144                                    userId);
19145                            if (userIdToKill == UserHandle.USER_ALL
19146                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19147                                // If gids changed for this user, kill all affected packages.
19148                                mHandler.post(new Runnable() {
19149                                    @Override
19150                                    public void run() {
19151                                        // This has to happen with no lock held.
19152                                        killApplication(deletedPs.name, deletedPs.appId,
19153                                                KILL_APP_REASON_GIDS_CHANGED);
19154                                    }
19155                                });
19156                                break;
19157                            }
19158                        }
19159                    }
19160                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19161                }
19162                // make sure to preserve per-user disabled state if this removal was just
19163                // a downgrade of a system app to the factory package
19164                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19165                    if (DEBUG_REMOVE) {
19166                        Slog.d(TAG, "Propagating install state across downgrade");
19167                    }
19168                    for (int userId : allUserHandles) {
19169                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19170                        if (DEBUG_REMOVE) {
19171                            Slog.d(TAG, "    user " + userId + " => " + installed);
19172                        }
19173                        if (installed != ps.getInstalled(userId)) {
19174                            installedStateChanged = true;
19175                        }
19176                        ps.setInstalled(installed, userId);
19177                    }
19178                }
19179            }
19180            // can downgrade to reader
19181            if (writeSettings) {
19182                // Save settings now
19183                mSettings.writeLPr();
19184            }
19185            if (installedStateChanged) {
19186                mSettings.writeKernelMappingLPr(ps);
19187            }
19188        }
19189        if (removedAppId != -1) {
19190            // A user ID was deleted here. Go through all users and remove it
19191            // from KeyStore.
19192            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19193        }
19194    }
19195
19196    static boolean locationIsPrivileged(File path) {
19197        try {
19198            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19199                    .getCanonicalPath();
19200            return path.getCanonicalPath().startsWith(privilegedAppDir);
19201        } catch (IOException e) {
19202            Slog.e(TAG, "Unable to access code path " + path);
19203        }
19204        return false;
19205    }
19206
19207    /*
19208     * Tries to delete system package.
19209     */
19210    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19211            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19212            boolean writeSettings) {
19213        if (deletedPs.parentPackageName != null) {
19214            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19215            return false;
19216        }
19217
19218        final boolean applyUserRestrictions
19219                = (allUserHandles != null) && (outInfo.origUsers != null);
19220        final PackageSetting disabledPs;
19221        // Confirm if the system package has been updated
19222        // An updated system app can be deleted. This will also have to restore
19223        // the system pkg from system partition
19224        // reader
19225        synchronized (mPackages) {
19226            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19227        }
19228
19229        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19230                + " disabledPs=" + disabledPs);
19231
19232        if (disabledPs == null) {
19233            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19234            return false;
19235        } else if (DEBUG_REMOVE) {
19236            Slog.d(TAG, "Deleting system pkg from data partition");
19237        }
19238
19239        if (DEBUG_REMOVE) {
19240            if (applyUserRestrictions) {
19241                Slog.d(TAG, "Remembering install states:");
19242                for (int userId : allUserHandles) {
19243                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19244                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19245                }
19246            }
19247        }
19248
19249        // Delete the updated package
19250        outInfo.isRemovedPackageSystemUpdate = true;
19251        if (outInfo.removedChildPackages != null) {
19252            final int childCount = (deletedPs.childPackageNames != null)
19253                    ? deletedPs.childPackageNames.size() : 0;
19254            for (int i = 0; i < childCount; i++) {
19255                String childPackageName = deletedPs.childPackageNames.get(i);
19256                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19257                        .contains(childPackageName)) {
19258                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19259                            childPackageName);
19260                    if (childInfo != null) {
19261                        childInfo.isRemovedPackageSystemUpdate = true;
19262                    }
19263                }
19264            }
19265        }
19266
19267        if (disabledPs.versionCode < deletedPs.versionCode) {
19268            // Delete data for downgrades
19269            flags &= ~PackageManager.DELETE_KEEP_DATA;
19270        } else {
19271            // Preserve data by setting flag
19272            flags |= PackageManager.DELETE_KEEP_DATA;
19273        }
19274
19275        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19276                outInfo, writeSettings, disabledPs.pkg);
19277        if (!ret) {
19278            return false;
19279        }
19280
19281        // writer
19282        synchronized (mPackages) {
19283            // Reinstate the old system package
19284            enableSystemPackageLPw(disabledPs.pkg);
19285            // Remove any native libraries from the upgraded package.
19286            removeNativeBinariesLI(deletedPs);
19287        }
19288
19289        // Install the system package
19290        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19291        int parseFlags = mDefParseFlags
19292                | PackageParser.PARSE_MUST_BE_APK
19293                | PackageParser.PARSE_IS_SYSTEM
19294                | PackageParser.PARSE_IS_SYSTEM_DIR;
19295        if (locationIsPrivileged(disabledPs.codePath)) {
19296            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19297        }
19298
19299        final PackageParser.Package newPkg;
19300        try {
19301            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19302                0 /* currentTime */, null);
19303        } catch (PackageManagerException e) {
19304            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19305                    + e.getMessage());
19306            return false;
19307        }
19308
19309        try {
19310            // update shared libraries for the newly re-installed system package
19311            updateSharedLibrariesLPr(newPkg, null);
19312        } catch (PackageManagerException e) {
19313            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19314        }
19315
19316        prepareAppDataAfterInstallLIF(newPkg);
19317
19318        // writer
19319        synchronized (mPackages) {
19320            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19321
19322            // Propagate the permissions state as we do not want to drop on the floor
19323            // runtime permissions. The update permissions method below will take
19324            // care of removing obsolete permissions and grant install permissions.
19325            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19326            updatePermissionsLPw(newPkg.packageName, newPkg,
19327                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19328
19329            if (applyUserRestrictions) {
19330                boolean installedStateChanged = false;
19331                if (DEBUG_REMOVE) {
19332                    Slog.d(TAG, "Propagating install state across reinstall");
19333                }
19334                for (int userId : allUserHandles) {
19335                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19336                    if (DEBUG_REMOVE) {
19337                        Slog.d(TAG, "    user " + userId + " => " + installed);
19338                    }
19339                    if (installed != ps.getInstalled(userId)) {
19340                        installedStateChanged = true;
19341                    }
19342                    ps.setInstalled(installed, userId);
19343
19344                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19345                }
19346                // Regardless of writeSettings we need to ensure that this restriction
19347                // state propagation is persisted
19348                mSettings.writeAllUsersPackageRestrictionsLPr();
19349                if (installedStateChanged) {
19350                    mSettings.writeKernelMappingLPr(ps);
19351                }
19352            }
19353            // can downgrade to reader here
19354            if (writeSettings) {
19355                mSettings.writeLPr();
19356            }
19357        }
19358        return true;
19359    }
19360
19361    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19362            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19363            PackageRemovedInfo outInfo, boolean writeSettings,
19364            PackageParser.Package replacingPackage) {
19365        synchronized (mPackages) {
19366            if (outInfo != null) {
19367                outInfo.uid = ps.appId;
19368            }
19369
19370            if (outInfo != null && outInfo.removedChildPackages != null) {
19371                final int childCount = (ps.childPackageNames != null)
19372                        ? ps.childPackageNames.size() : 0;
19373                for (int i = 0; i < childCount; i++) {
19374                    String childPackageName = ps.childPackageNames.get(i);
19375                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19376                    if (childPs == null) {
19377                        return false;
19378                    }
19379                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19380                            childPackageName);
19381                    if (childInfo != null) {
19382                        childInfo.uid = childPs.appId;
19383                    }
19384                }
19385            }
19386        }
19387
19388        // Delete package data from internal structures and also remove data if flag is set
19389        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19390
19391        // Delete the child packages data
19392        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19393        for (int i = 0; i < childCount; i++) {
19394            PackageSetting childPs;
19395            synchronized (mPackages) {
19396                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19397            }
19398            if (childPs != null) {
19399                PackageRemovedInfo childOutInfo = (outInfo != null
19400                        && outInfo.removedChildPackages != null)
19401                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19402                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19403                        && (replacingPackage != null
19404                        && !replacingPackage.hasChildPackage(childPs.name))
19405                        ? flags & ~DELETE_KEEP_DATA : flags;
19406                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19407                        deleteFlags, writeSettings);
19408            }
19409        }
19410
19411        // Delete application code and resources only for parent packages
19412        if (ps.parentPackageName == null) {
19413            if (deleteCodeAndResources && (outInfo != null)) {
19414                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19415                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19416                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19417            }
19418        }
19419
19420        return true;
19421    }
19422
19423    @Override
19424    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19425            int userId) {
19426        mContext.enforceCallingOrSelfPermission(
19427                android.Manifest.permission.DELETE_PACKAGES, null);
19428        synchronized (mPackages) {
19429            // Cannot block uninstall of static shared libs as they are
19430            // considered a part of the using app (emulating static linking).
19431            // Also static libs are installed always on internal storage.
19432            PackageParser.Package pkg = mPackages.get(packageName);
19433            if (pkg != null && pkg.staticSharedLibName != null) {
19434                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19435                        + " providing static shared library: " + pkg.staticSharedLibName);
19436                return false;
19437            }
19438            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19439            mSettings.writePackageRestrictionsLPr(userId);
19440        }
19441        return true;
19442    }
19443
19444    @Override
19445    public boolean getBlockUninstallForUser(String packageName, int userId) {
19446        synchronized (mPackages) {
19447            final PackageSetting ps = mSettings.mPackages.get(packageName);
19448            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19449                return false;
19450            }
19451            return mSettings.getBlockUninstallLPr(userId, packageName);
19452        }
19453    }
19454
19455    @Override
19456    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19457        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19458        synchronized (mPackages) {
19459            PackageSetting ps = mSettings.mPackages.get(packageName);
19460            if (ps == null) {
19461                Log.w(TAG, "Package doesn't exist: " + packageName);
19462                return false;
19463            }
19464            if (systemUserApp) {
19465                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19466            } else {
19467                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19468            }
19469            mSettings.writeLPr();
19470        }
19471        return true;
19472    }
19473
19474    /*
19475     * This method handles package deletion in general
19476     */
19477    private boolean deletePackageLIF(String packageName, UserHandle user,
19478            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19479            PackageRemovedInfo outInfo, boolean writeSettings,
19480            PackageParser.Package replacingPackage) {
19481        if (packageName == null) {
19482            Slog.w(TAG, "Attempt to delete null packageName.");
19483            return false;
19484        }
19485
19486        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19487
19488        PackageSetting ps;
19489        synchronized (mPackages) {
19490            ps = mSettings.mPackages.get(packageName);
19491            if (ps == null) {
19492                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19493                return false;
19494            }
19495
19496            if (ps.parentPackageName != null && (!isSystemApp(ps)
19497                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19498                if (DEBUG_REMOVE) {
19499                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19500                            + ((user == null) ? UserHandle.USER_ALL : user));
19501                }
19502                final int removedUserId = (user != null) ? user.getIdentifier()
19503                        : UserHandle.USER_ALL;
19504                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19505                    return false;
19506                }
19507                markPackageUninstalledForUserLPw(ps, user);
19508                scheduleWritePackageRestrictionsLocked(user);
19509                return true;
19510            }
19511        }
19512
19513        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19514                && user.getIdentifier() != UserHandle.USER_ALL)) {
19515            // The caller is asking that the package only be deleted for a single
19516            // user.  To do this, we just mark its uninstalled state and delete
19517            // its data. If this is a system app, we only allow this to happen if
19518            // they have set the special DELETE_SYSTEM_APP which requests different
19519            // semantics than normal for uninstalling system apps.
19520            markPackageUninstalledForUserLPw(ps, user);
19521
19522            if (!isSystemApp(ps)) {
19523                // Do not uninstall the APK if an app should be cached
19524                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19525                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19526                    // Other user still have this package installed, so all
19527                    // we need to do is clear this user's data and save that
19528                    // it is uninstalled.
19529                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19530                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19531                        return false;
19532                    }
19533                    scheduleWritePackageRestrictionsLocked(user);
19534                    return true;
19535                } else {
19536                    // We need to set it back to 'installed' so the uninstall
19537                    // broadcasts will be sent correctly.
19538                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19539                    ps.setInstalled(true, user.getIdentifier());
19540                    mSettings.writeKernelMappingLPr(ps);
19541                }
19542            } else {
19543                // This is a system app, so we assume that the
19544                // other users still have this package installed, so all
19545                // we need to do is clear this user's data and save that
19546                // it is uninstalled.
19547                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19548                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19549                    return false;
19550                }
19551                scheduleWritePackageRestrictionsLocked(user);
19552                return true;
19553            }
19554        }
19555
19556        // If we are deleting a composite package for all users, keep track
19557        // of result for each child.
19558        if (ps.childPackageNames != null && outInfo != null) {
19559            synchronized (mPackages) {
19560                final int childCount = ps.childPackageNames.size();
19561                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19562                for (int i = 0; i < childCount; i++) {
19563                    String childPackageName = ps.childPackageNames.get(i);
19564                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19565                    childInfo.removedPackage = childPackageName;
19566                    childInfo.installerPackageName = ps.installerPackageName;
19567                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19568                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19569                    if (childPs != null) {
19570                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19571                    }
19572                }
19573            }
19574        }
19575
19576        boolean ret = false;
19577        if (isSystemApp(ps)) {
19578            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19579            // When an updated system application is deleted we delete the existing resources
19580            // as well and fall back to existing code in system partition
19581            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19582        } else {
19583            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19584            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19585                    outInfo, writeSettings, replacingPackage);
19586        }
19587
19588        // Take a note whether we deleted the package for all users
19589        if (outInfo != null) {
19590            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19591            if (outInfo.removedChildPackages != null) {
19592                synchronized (mPackages) {
19593                    final int childCount = outInfo.removedChildPackages.size();
19594                    for (int i = 0; i < childCount; i++) {
19595                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19596                        if (childInfo != null) {
19597                            childInfo.removedForAllUsers = mPackages.get(
19598                                    childInfo.removedPackage) == null;
19599                        }
19600                    }
19601                }
19602            }
19603            // If we uninstalled an update to a system app there may be some
19604            // child packages that appeared as they are declared in the system
19605            // app but were not declared in the update.
19606            if (isSystemApp(ps)) {
19607                synchronized (mPackages) {
19608                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19609                    final int childCount = (updatedPs.childPackageNames != null)
19610                            ? updatedPs.childPackageNames.size() : 0;
19611                    for (int i = 0; i < childCount; i++) {
19612                        String childPackageName = updatedPs.childPackageNames.get(i);
19613                        if (outInfo.removedChildPackages == null
19614                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19615                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19616                            if (childPs == null) {
19617                                continue;
19618                            }
19619                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19620                            installRes.name = childPackageName;
19621                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19622                            installRes.pkg = mPackages.get(childPackageName);
19623                            installRes.uid = childPs.pkg.applicationInfo.uid;
19624                            if (outInfo.appearedChildPackages == null) {
19625                                outInfo.appearedChildPackages = new ArrayMap<>();
19626                            }
19627                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19628                        }
19629                    }
19630                }
19631            }
19632        }
19633
19634        return ret;
19635    }
19636
19637    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19638        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19639                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19640        for (int nextUserId : userIds) {
19641            if (DEBUG_REMOVE) {
19642                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19643            }
19644            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19645                    false /*installed*/,
19646                    true /*stopped*/,
19647                    true /*notLaunched*/,
19648                    false /*hidden*/,
19649                    false /*suspended*/,
19650                    false /*instantApp*/,
19651                    null /*lastDisableAppCaller*/,
19652                    null /*enabledComponents*/,
19653                    null /*disabledComponents*/,
19654                    ps.readUserState(nextUserId).domainVerificationStatus,
19655                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19656        }
19657        mSettings.writeKernelMappingLPr(ps);
19658    }
19659
19660    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19661            PackageRemovedInfo outInfo) {
19662        final PackageParser.Package pkg;
19663        synchronized (mPackages) {
19664            pkg = mPackages.get(ps.name);
19665        }
19666
19667        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19668                : new int[] {userId};
19669        for (int nextUserId : userIds) {
19670            if (DEBUG_REMOVE) {
19671                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19672                        + nextUserId);
19673            }
19674
19675            destroyAppDataLIF(pkg, userId,
19676                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19677            destroyAppProfilesLIF(pkg, userId);
19678            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19679            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19680            schedulePackageCleaning(ps.name, nextUserId, false);
19681            synchronized (mPackages) {
19682                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19683                    scheduleWritePackageRestrictionsLocked(nextUserId);
19684                }
19685                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19686            }
19687        }
19688
19689        if (outInfo != null) {
19690            outInfo.removedPackage = ps.name;
19691            outInfo.installerPackageName = ps.installerPackageName;
19692            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19693            outInfo.removedAppId = ps.appId;
19694            outInfo.removedUsers = userIds;
19695            outInfo.broadcastUsers = userIds;
19696        }
19697
19698        return true;
19699    }
19700
19701    private final class ClearStorageConnection implements ServiceConnection {
19702        IMediaContainerService mContainerService;
19703
19704        @Override
19705        public void onServiceConnected(ComponentName name, IBinder service) {
19706            synchronized (this) {
19707                mContainerService = IMediaContainerService.Stub
19708                        .asInterface(Binder.allowBlocking(service));
19709                notifyAll();
19710            }
19711        }
19712
19713        @Override
19714        public void onServiceDisconnected(ComponentName name) {
19715        }
19716    }
19717
19718    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19719        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19720
19721        final boolean mounted;
19722        if (Environment.isExternalStorageEmulated()) {
19723            mounted = true;
19724        } else {
19725            final String status = Environment.getExternalStorageState();
19726
19727            mounted = status.equals(Environment.MEDIA_MOUNTED)
19728                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19729        }
19730
19731        if (!mounted) {
19732            return;
19733        }
19734
19735        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19736        int[] users;
19737        if (userId == UserHandle.USER_ALL) {
19738            users = sUserManager.getUserIds();
19739        } else {
19740            users = new int[] { userId };
19741        }
19742        final ClearStorageConnection conn = new ClearStorageConnection();
19743        if (mContext.bindServiceAsUser(
19744                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19745            try {
19746                for (int curUser : users) {
19747                    long timeout = SystemClock.uptimeMillis() + 5000;
19748                    synchronized (conn) {
19749                        long now;
19750                        while (conn.mContainerService == null &&
19751                                (now = SystemClock.uptimeMillis()) < timeout) {
19752                            try {
19753                                conn.wait(timeout - now);
19754                            } catch (InterruptedException e) {
19755                            }
19756                        }
19757                    }
19758                    if (conn.mContainerService == null) {
19759                        return;
19760                    }
19761
19762                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19763                    clearDirectory(conn.mContainerService,
19764                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19765                    if (allData) {
19766                        clearDirectory(conn.mContainerService,
19767                                userEnv.buildExternalStorageAppDataDirs(packageName));
19768                        clearDirectory(conn.mContainerService,
19769                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19770                    }
19771                }
19772            } finally {
19773                mContext.unbindService(conn);
19774            }
19775        }
19776    }
19777
19778    @Override
19779    public void clearApplicationProfileData(String packageName) {
19780        enforceSystemOrRoot("Only the system can clear all profile data");
19781
19782        final PackageParser.Package pkg;
19783        synchronized (mPackages) {
19784            pkg = mPackages.get(packageName);
19785        }
19786
19787        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19788            synchronized (mInstallLock) {
19789                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19790            }
19791        }
19792    }
19793
19794    @Override
19795    public void clearApplicationUserData(final String packageName,
19796            final IPackageDataObserver observer, final int userId) {
19797        mContext.enforceCallingOrSelfPermission(
19798                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19799
19800        final int callingUid = Binder.getCallingUid();
19801        enforceCrossUserPermission(callingUid, userId,
19802                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19803
19804        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19805        if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
19806            return;
19807        }
19808        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19809            throw new SecurityException("Cannot clear data for a protected package: "
19810                    + packageName);
19811        }
19812        // Queue up an async operation since the package deletion may take a little while.
19813        mHandler.post(new Runnable() {
19814            public void run() {
19815                mHandler.removeCallbacks(this);
19816                final boolean succeeded;
19817                try (PackageFreezer freezer = freezePackage(packageName,
19818                        "clearApplicationUserData")) {
19819                    synchronized (mInstallLock) {
19820                        succeeded = clearApplicationUserDataLIF(packageName, userId);
19821                    }
19822                    clearExternalStorageDataSync(packageName, userId, true);
19823                    synchronized (mPackages) {
19824                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19825                                packageName, userId);
19826                    }
19827                }
19828                if (succeeded) {
19829                    // invoke DeviceStorageMonitor's update method to clear any notifications
19830                    DeviceStorageMonitorInternal dsm = LocalServices
19831                            .getService(DeviceStorageMonitorInternal.class);
19832                    if (dsm != null) {
19833                        dsm.checkMemory();
19834                    }
19835                }
19836                if(observer != null) {
19837                    try {
19838                        observer.onRemoveCompleted(packageName, succeeded);
19839                    } catch (RemoteException e) {
19840                        Log.i(TAG, "Observer no longer exists.");
19841                    }
19842                } //end if observer
19843            } //end run
19844        });
19845    }
19846
19847    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19848        if (packageName == null) {
19849            Slog.w(TAG, "Attempt to delete null packageName.");
19850            return false;
19851        }
19852
19853        // Try finding details about the requested package
19854        PackageParser.Package pkg;
19855        synchronized (mPackages) {
19856            pkg = mPackages.get(packageName);
19857            if (pkg == null) {
19858                final PackageSetting ps = mSettings.mPackages.get(packageName);
19859                if (ps != null) {
19860                    pkg = ps.pkg;
19861                }
19862            }
19863
19864            if (pkg == null) {
19865                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19866                return false;
19867            }
19868
19869            PackageSetting ps = (PackageSetting) pkg.mExtras;
19870            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19871        }
19872
19873        clearAppDataLIF(pkg, userId,
19874                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19875
19876        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19877        removeKeystoreDataIfNeeded(userId, appId);
19878
19879        UserManagerInternal umInternal = getUserManagerInternal();
19880        final int flags;
19881        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19882            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19883        } else if (umInternal.isUserRunning(userId)) {
19884            flags = StorageManager.FLAG_STORAGE_DE;
19885        } else {
19886            flags = 0;
19887        }
19888        prepareAppDataContentsLIF(pkg, userId, flags);
19889
19890        return true;
19891    }
19892
19893    /**
19894     * Reverts user permission state changes (permissions and flags) in
19895     * all packages for a given user.
19896     *
19897     * @param userId The device user for which to do a reset.
19898     */
19899    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19900        final int packageCount = mPackages.size();
19901        for (int i = 0; i < packageCount; i++) {
19902            PackageParser.Package pkg = mPackages.valueAt(i);
19903            PackageSetting ps = (PackageSetting) pkg.mExtras;
19904            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19905        }
19906    }
19907
19908    private void resetNetworkPolicies(int userId) {
19909        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19910    }
19911
19912    /**
19913     * Reverts user permission state changes (permissions and flags).
19914     *
19915     * @param ps The package for which to reset.
19916     * @param userId The device user for which to do a reset.
19917     */
19918    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19919            final PackageSetting ps, final int userId) {
19920        if (ps.pkg == null) {
19921            return;
19922        }
19923
19924        // These are flags that can change base on user actions.
19925        final int userSettableMask = FLAG_PERMISSION_USER_SET
19926                | FLAG_PERMISSION_USER_FIXED
19927                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19928                | FLAG_PERMISSION_REVIEW_REQUIRED;
19929
19930        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19931                | FLAG_PERMISSION_POLICY_FIXED;
19932
19933        boolean writeInstallPermissions = false;
19934        boolean writeRuntimePermissions = false;
19935
19936        final int permissionCount = ps.pkg.requestedPermissions.size();
19937        for (int i = 0; i < permissionCount; i++) {
19938            String permission = ps.pkg.requestedPermissions.get(i);
19939
19940            BasePermission bp = mSettings.mPermissions.get(permission);
19941            if (bp == null) {
19942                continue;
19943            }
19944
19945            // If shared user we just reset the state to which only this app contributed.
19946            if (ps.sharedUser != null) {
19947                boolean used = false;
19948                final int packageCount = ps.sharedUser.packages.size();
19949                for (int j = 0; j < packageCount; j++) {
19950                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19951                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19952                            && pkg.pkg.requestedPermissions.contains(permission)) {
19953                        used = true;
19954                        break;
19955                    }
19956                }
19957                if (used) {
19958                    continue;
19959                }
19960            }
19961
19962            PermissionsState permissionsState = ps.getPermissionsState();
19963
19964            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
19965
19966            // Always clear the user settable flags.
19967            final boolean hasInstallState = permissionsState.getInstallPermissionState(
19968                    bp.name) != null;
19969            // If permission review is enabled and this is a legacy app, mark the
19970            // permission as requiring a review as this is the initial state.
19971            int flags = 0;
19972            if (mPermissionReviewRequired
19973                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19974                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19975            }
19976            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19977                if (hasInstallState) {
19978                    writeInstallPermissions = true;
19979                } else {
19980                    writeRuntimePermissions = true;
19981                }
19982            }
19983
19984            // Below is only runtime permission handling.
19985            if (!bp.isRuntime()) {
19986                continue;
19987            }
19988
19989            // Never clobber system or policy.
19990            if ((oldFlags & policyOrSystemFlags) != 0) {
19991                continue;
19992            }
19993
19994            // If this permission was granted by default, make sure it is.
19995            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19996                if (permissionsState.grantRuntimePermission(bp, userId)
19997                        != PERMISSION_OPERATION_FAILURE) {
19998                    writeRuntimePermissions = true;
19999                }
20000            // If permission review is enabled the permissions for a legacy apps
20001            // are represented as constantly granted runtime ones, so don't revoke.
20002            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20003                // Otherwise, reset the permission.
20004                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20005                switch (revokeResult) {
20006                    case PERMISSION_OPERATION_SUCCESS:
20007                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20008                        writeRuntimePermissions = true;
20009                        final int appId = ps.appId;
20010                        mHandler.post(new Runnable() {
20011                            @Override
20012                            public void run() {
20013                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20014                            }
20015                        });
20016                    } break;
20017                }
20018            }
20019        }
20020
20021        // Synchronously write as we are taking permissions away.
20022        if (writeRuntimePermissions) {
20023            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20024        }
20025
20026        // Synchronously write as we are taking permissions away.
20027        if (writeInstallPermissions) {
20028            mSettings.writeLPr();
20029        }
20030    }
20031
20032    /**
20033     * Remove entries from the keystore daemon. Will only remove it if the
20034     * {@code appId} is valid.
20035     */
20036    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20037        if (appId < 0) {
20038            return;
20039        }
20040
20041        final KeyStore keyStore = KeyStore.getInstance();
20042        if (keyStore != null) {
20043            if (userId == UserHandle.USER_ALL) {
20044                for (final int individual : sUserManager.getUserIds()) {
20045                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20046                }
20047            } else {
20048                keyStore.clearUid(UserHandle.getUid(userId, appId));
20049            }
20050        } else {
20051            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20052        }
20053    }
20054
20055    @Override
20056    public void deleteApplicationCacheFiles(final String packageName,
20057            final IPackageDataObserver observer) {
20058        final int userId = UserHandle.getCallingUserId();
20059        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20060    }
20061
20062    @Override
20063    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20064            final IPackageDataObserver observer) {
20065        final int callingUid = Binder.getCallingUid();
20066        mContext.enforceCallingOrSelfPermission(
20067                android.Manifest.permission.DELETE_CACHE_FILES, null);
20068        enforceCrossUserPermission(callingUid, userId,
20069                /* requireFullPermission= */ true, /* checkShell= */ false,
20070                "delete application cache files");
20071        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20072                android.Manifest.permission.ACCESS_INSTANT_APPS);
20073
20074        final PackageParser.Package pkg;
20075        synchronized (mPackages) {
20076            pkg = mPackages.get(packageName);
20077        }
20078
20079        // Queue up an async operation since the package deletion may take a little while.
20080        mHandler.post(new Runnable() {
20081            public void run() {
20082                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20083                boolean doClearData = true;
20084                if (ps != null) {
20085                    final boolean targetIsInstantApp =
20086                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20087                    doClearData = !targetIsInstantApp
20088                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20089                }
20090                if (doClearData) {
20091                    synchronized (mInstallLock) {
20092                        final int flags = StorageManager.FLAG_STORAGE_DE
20093                                | StorageManager.FLAG_STORAGE_CE;
20094                        // We're only clearing cache files, so we don't care if the
20095                        // app is unfrozen and still able to run
20096                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20097                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20098                    }
20099                    clearExternalStorageDataSync(packageName, userId, false);
20100                }
20101                if (observer != null) {
20102                    try {
20103                        observer.onRemoveCompleted(packageName, true);
20104                    } catch (RemoteException e) {
20105                        Log.i(TAG, "Observer no longer exists.");
20106                    }
20107                }
20108            }
20109        });
20110    }
20111
20112    @Override
20113    public void getPackageSizeInfo(final String packageName, int userHandle,
20114            final IPackageStatsObserver observer) {
20115        throw new UnsupportedOperationException(
20116                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20117    }
20118
20119    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20120        final PackageSetting ps;
20121        synchronized (mPackages) {
20122            ps = mSettings.mPackages.get(packageName);
20123            if (ps == null) {
20124                Slog.w(TAG, "Failed to find settings for " + packageName);
20125                return false;
20126            }
20127        }
20128
20129        final String[] packageNames = { packageName };
20130        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20131        final String[] codePaths = { ps.codePathString };
20132
20133        try {
20134            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20135                    ps.appId, ceDataInodes, codePaths, stats);
20136
20137            // For now, ignore code size of packages on system partition
20138            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20139                stats.codeSize = 0;
20140            }
20141
20142            // External clients expect these to be tracked separately
20143            stats.dataSize -= stats.cacheSize;
20144
20145        } catch (InstallerException e) {
20146            Slog.w(TAG, String.valueOf(e));
20147            return false;
20148        }
20149
20150        return true;
20151    }
20152
20153    private int getUidTargetSdkVersionLockedLPr(int uid) {
20154        Object obj = mSettings.getUserIdLPr(uid);
20155        if (obj instanceof SharedUserSetting) {
20156            final SharedUserSetting sus = (SharedUserSetting) obj;
20157            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20158            final Iterator<PackageSetting> it = sus.packages.iterator();
20159            while (it.hasNext()) {
20160                final PackageSetting ps = it.next();
20161                if (ps.pkg != null) {
20162                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20163                    if (v < vers) vers = v;
20164                }
20165            }
20166            return vers;
20167        } else if (obj instanceof PackageSetting) {
20168            final PackageSetting ps = (PackageSetting) obj;
20169            if (ps.pkg != null) {
20170                return ps.pkg.applicationInfo.targetSdkVersion;
20171            }
20172        }
20173        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20174    }
20175
20176    @Override
20177    public void addPreferredActivity(IntentFilter filter, int match,
20178            ComponentName[] set, ComponentName activity, int userId) {
20179        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20180                "Adding preferred");
20181    }
20182
20183    private void addPreferredActivityInternal(IntentFilter filter, int match,
20184            ComponentName[] set, ComponentName activity, boolean always, int userId,
20185            String opname) {
20186        // writer
20187        int callingUid = Binder.getCallingUid();
20188        enforceCrossUserPermission(callingUid, userId,
20189                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20190        if (filter.countActions() == 0) {
20191            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20192            return;
20193        }
20194        synchronized (mPackages) {
20195            if (mContext.checkCallingOrSelfPermission(
20196                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20197                    != PackageManager.PERMISSION_GRANTED) {
20198                if (getUidTargetSdkVersionLockedLPr(callingUid)
20199                        < Build.VERSION_CODES.FROYO) {
20200                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20201                            + callingUid);
20202                    return;
20203                }
20204                mContext.enforceCallingOrSelfPermission(
20205                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20206            }
20207
20208            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20209            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20210                    + userId + ":");
20211            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20212            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20213            scheduleWritePackageRestrictionsLocked(userId);
20214            postPreferredActivityChangedBroadcast(userId);
20215        }
20216    }
20217
20218    private void postPreferredActivityChangedBroadcast(int userId) {
20219        mHandler.post(() -> {
20220            final IActivityManager am = ActivityManager.getService();
20221            if (am == null) {
20222                return;
20223            }
20224
20225            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20226            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20227            try {
20228                am.broadcastIntent(null, intent, null, null,
20229                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20230                        null, false, false, userId);
20231            } catch (RemoteException e) {
20232            }
20233        });
20234    }
20235
20236    @Override
20237    public void replacePreferredActivity(IntentFilter filter, int match,
20238            ComponentName[] set, ComponentName activity, int userId) {
20239        if (filter.countActions() != 1) {
20240            throw new IllegalArgumentException(
20241                    "replacePreferredActivity expects filter to have only 1 action.");
20242        }
20243        if (filter.countDataAuthorities() != 0
20244                || filter.countDataPaths() != 0
20245                || filter.countDataSchemes() > 1
20246                || filter.countDataTypes() != 0) {
20247            throw new IllegalArgumentException(
20248                    "replacePreferredActivity expects filter to have no data authorities, " +
20249                    "paths, or types; and at most one scheme.");
20250        }
20251
20252        final int callingUid = Binder.getCallingUid();
20253        enforceCrossUserPermission(callingUid, userId,
20254                true /* requireFullPermission */, false /* checkShell */,
20255                "replace preferred activity");
20256        synchronized (mPackages) {
20257            if (mContext.checkCallingOrSelfPermission(
20258                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20259                    != PackageManager.PERMISSION_GRANTED) {
20260                if (getUidTargetSdkVersionLockedLPr(callingUid)
20261                        < Build.VERSION_CODES.FROYO) {
20262                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20263                            + Binder.getCallingUid());
20264                    return;
20265                }
20266                mContext.enforceCallingOrSelfPermission(
20267                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20268            }
20269
20270            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20271            if (pir != null) {
20272                // Get all of the existing entries that exactly match this filter.
20273                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20274                if (existing != null && existing.size() == 1) {
20275                    PreferredActivity cur = existing.get(0);
20276                    if (DEBUG_PREFERRED) {
20277                        Slog.i(TAG, "Checking replace of preferred:");
20278                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20279                        if (!cur.mPref.mAlways) {
20280                            Slog.i(TAG, "  -- CUR; not mAlways!");
20281                        } else {
20282                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20283                            Slog.i(TAG, "  -- CUR: mSet="
20284                                    + Arrays.toString(cur.mPref.mSetComponents));
20285                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20286                            Slog.i(TAG, "  -- NEW: mMatch="
20287                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20288                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20289                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20290                        }
20291                    }
20292                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20293                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20294                            && cur.mPref.sameSet(set)) {
20295                        // Setting the preferred activity to what it happens to be already
20296                        if (DEBUG_PREFERRED) {
20297                            Slog.i(TAG, "Replacing with same preferred activity "
20298                                    + cur.mPref.mShortComponent + " for user "
20299                                    + userId + ":");
20300                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20301                        }
20302                        return;
20303                    }
20304                }
20305
20306                if (existing != null) {
20307                    if (DEBUG_PREFERRED) {
20308                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20309                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20310                    }
20311                    for (int i = 0; i < existing.size(); i++) {
20312                        PreferredActivity pa = existing.get(i);
20313                        if (DEBUG_PREFERRED) {
20314                            Slog.i(TAG, "Removing existing preferred activity "
20315                                    + pa.mPref.mComponent + ":");
20316                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20317                        }
20318                        pir.removeFilter(pa);
20319                    }
20320                }
20321            }
20322            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20323                    "Replacing preferred");
20324        }
20325    }
20326
20327    @Override
20328    public void clearPackagePreferredActivities(String packageName) {
20329        final int callingUid = Binder.getCallingUid();
20330        if (getInstantAppPackageName(callingUid) != null) {
20331            return;
20332        }
20333        // writer
20334        synchronized (mPackages) {
20335            PackageParser.Package pkg = mPackages.get(packageName);
20336            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20337                if (mContext.checkCallingOrSelfPermission(
20338                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20339                        != PackageManager.PERMISSION_GRANTED) {
20340                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20341                            < Build.VERSION_CODES.FROYO) {
20342                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20343                                + callingUid);
20344                        return;
20345                    }
20346                    mContext.enforceCallingOrSelfPermission(
20347                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20348                }
20349            }
20350            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20351            if (ps != null
20352                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20353                return;
20354            }
20355            int user = UserHandle.getCallingUserId();
20356            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20357                scheduleWritePackageRestrictionsLocked(user);
20358            }
20359        }
20360    }
20361
20362    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20363    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20364        ArrayList<PreferredActivity> removed = null;
20365        boolean changed = false;
20366        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20367            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20368            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20369            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20370                continue;
20371            }
20372            Iterator<PreferredActivity> it = pir.filterIterator();
20373            while (it.hasNext()) {
20374                PreferredActivity pa = it.next();
20375                // Mark entry for removal only if it matches the package name
20376                // and the entry is of type "always".
20377                if (packageName == null ||
20378                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20379                                && pa.mPref.mAlways)) {
20380                    if (removed == null) {
20381                        removed = new ArrayList<PreferredActivity>();
20382                    }
20383                    removed.add(pa);
20384                }
20385            }
20386            if (removed != null) {
20387                for (int j=0; j<removed.size(); j++) {
20388                    PreferredActivity pa = removed.get(j);
20389                    pir.removeFilter(pa);
20390                }
20391                changed = true;
20392            }
20393        }
20394        if (changed) {
20395            postPreferredActivityChangedBroadcast(userId);
20396        }
20397        return changed;
20398    }
20399
20400    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20401    private void clearIntentFilterVerificationsLPw(int userId) {
20402        final int packageCount = mPackages.size();
20403        for (int i = 0; i < packageCount; i++) {
20404            PackageParser.Package pkg = mPackages.valueAt(i);
20405            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20406        }
20407    }
20408
20409    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20410    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20411        if (userId == UserHandle.USER_ALL) {
20412            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20413                    sUserManager.getUserIds())) {
20414                for (int oneUserId : sUserManager.getUserIds()) {
20415                    scheduleWritePackageRestrictionsLocked(oneUserId);
20416                }
20417            }
20418        } else {
20419            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20420                scheduleWritePackageRestrictionsLocked(userId);
20421            }
20422        }
20423    }
20424
20425    /** Clears state for all users, and touches intent filter verification policy */
20426    void clearDefaultBrowserIfNeeded(String packageName) {
20427        for (int oneUserId : sUserManager.getUserIds()) {
20428            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20429        }
20430    }
20431
20432    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20433        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20434        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20435            if (packageName.equals(defaultBrowserPackageName)) {
20436                setDefaultBrowserPackageName(null, userId);
20437            }
20438        }
20439    }
20440
20441    @Override
20442    public void resetApplicationPreferences(int userId) {
20443        mContext.enforceCallingOrSelfPermission(
20444                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20445        final long identity = Binder.clearCallingIdentity();
20446        // writer
20447        try {
20448            synchronized (mPackages) {
20449                clearPackagePreferredActivitiesLPw(null, userId);
20450                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20451                // TODO: We have to reset the default SMS and Phone. This requires
20452                // significant refactoring to keep all default apps in the package
20453                // manager (cleaner but more work) or have the services provide
20454                // callbacks to the package manager to request a default app reset.
20455                applyFactoryDefaultBrowserLPw(userId);
20456                clearIntentFilterVerificationsLPw(userId);
20457                primeDomainVerificationsLPw(userId);
20458                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20459                scheduleWritePackageRestrictionsLocked(userId);
20460            }
20461            resetNetworkPolicies(userId);
20462        } finally {
20463            Binder.restoreCallingIdentity(identity);
20464        }
20465    }
20466
20467    @Override
20468    public int getPreferredActivities(List<IntentFilter> outFilters,
20469            List<ComponentName> outActivities, String packageName) {
20470        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20471            return 0;
20472        }
20473        int num = 0;
20474        final int userId = UserHandle.getCallingUserId();
20475        // reader
20476        synchronized (mPackages) {
20477            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20478            if (pir != null) {
20479                final Iterator<PreferredActivity> it = pir.filterIterator();
20480                while (it.hasNext()) {
20481                    final PreferredActivity pa = it.next();
20482                    if (packageName == null
20483                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20484                                    && pa.mPref.mAlways)) {
20485                        if (outFilters != null) {
20486                            outFilters.add(new IntentFilter(pa));
20487                        }
20488                        if (outActivities != null) {
20489                            outActivities.add(pa.mPref.mComponent);
20490                        }
20491                    }
20492                }
20493            }
20494        }
20495
20496        return num;
20497    }
20498
20499    @Override
20500    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20501            int userId) {
20502        int callingUid = Binder.getCallingUid();
20503        if (callingUid != Process.SYSTEM_UID) {
20504            throw new SecurityException(
20505                    "addPersistentPreferredActivity can only be run by the system");
20506        }
20507        if (filter.countActions() == 0) {
20508            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20509            return;
20510        }
20511        synchronized (mPackages) {
20512            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20513                    ":");
20514            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20515            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20516                    new PersistentPreferredActivity(filter, activity));
20517            scheduleWritePackageRestrictionsLocked(userId);
20518            postPreferredActivityChangedBroadcast(userId);
20519        }
20520    }
20521
20522    @Override
20523    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20524        int callingUid = Binder.getCallingUid();
20525        if (callingUid != Process.SYSTEM_UID) {
20526            throw new SecurityException(
20527                    "clearPackagePersistentPreferredActivities can only be run by the system");
20528        }
20529        ArrayList<PersistentPreferredActivity> removed = null;
20530        boolean changed = false;
20531        synchronized (mPackages) {
20532            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20533                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20534                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20535                        .valueAt(i);
20536                if (userId != thisUserId) {
20537                    continue;
20538                }
20539                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20540                while (it.hasNext()) {
20541                    PersistentPreferredActivity ppa = it.next();
20542                    // Mark entry for removal only if it matches the package name.
20543                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20544                        if (removed == null) {
20545                            removed = new ArrayList<PersistentPreferredActivity>();
20546                        }
20547                        removed.add(ppa);
20548                    }
20549                }
20550                if (removed != null) {
20551                    for (int j=0; j<removed.size(); j++) {
20552                        PersistentPreferredActivity ppa = removed.get(j);
20553                        ppir.removeFilter(ppa);
20554                    }
20555                    changed = true;
20556                }
20557            }
20558
20559            if (changed) {
20560                scheduleWritePackageRestrictionsLocked(userId);
20561                postPreferredActivityChangedBroadcast(userId);
20562            }
20563        }
20564    }
20565
20566    /**
20567     * Common machinery for picking apart a restored XML blob and passing
20568     * it to a caller-supplied functor to be applied to the running system.
20569     */
20570    private void restoreFromXml(XmlPullParser parser, int userId,
20571            String expectedStartTag, BlobXmlRestorer functor)
20572            throws IOException, XmlPullParserException {
20573        int type;
20574        while ((type = parser.next()) != XmlPullParser.START_TAG
20575                && type != XmlPullParser.END_DOCUMENT) {
20576        }
20577        if (type != XmlPullParser.START_TAG) {
20578            // oops didn't find a start tag?!
20579            if (DEBUG_BACKUP) {
20580                Slog.e(TAG, "Didn't find start tag during restore");
20581            }
20582            return;
20583        }
20584Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20585        // this is supposed to be TAG_PREFERRED_BACKUP
20586        if (!expectedStartTag.equals(parser.getName())) {
20587            if (DEBUG_BACKUP) {
20588                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20589            }
20590            return;
20591        }
20592
20593        // skip interfering stuff, then we're aligned with the backing implementation
20594        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20595Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20596        functor.apply(parser, userId);
20597    }
20598
20599    private interface BlobXmlRestorer {
20600        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20601    }
20602
20603    /**
20604     * Non-Binder method, support for the backup/restore mechanism: write the
20605     * full set of preferred activities in its canonical XML format.  Returns the
20606     * XML output as a byte array, or null if there is none.
20607     */
20608    @Override
20609    public byte[] getPreferredActivityBackup(int userId) {
20610        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20611            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20612        }
20613
20614        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20615        try {
20616            final XmlSerializer serializer = new FastXmlSerializer();
20617            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20618            serializer.startDocument(null, true);
20619            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20620
20621            synchronized (mPackages) {
20622                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20623            }
20624
20625            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20626            serializer.endDocument();
20627            serializer.flush();
20628        } catch (Exception e) {
20629            if (DEBUG_BACKUP) {
20630                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20631            }
20632            return null;
20633        }
20634
20635        return dataStream.toByteArray();
20636    }
20637
20638    @Override
20639    public void restorePreferredActivities(byte[] backup, int userId) {
20640        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20641            throw new SecurityException("Only the system may call restorePreferredActivities()");
20642        }
20643
20644        try {
20645            final XmlPullParser parser = Xml.newPullParser();
20646            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20647            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20648                    new BlobXmlRestorer() {
20649                        @Override
20650                        public void apply(XmlPullParser parser, int userId)
20651                                throws XmlPullParserException, IOException {
20652                            synchronized (mPackages) {
20653                                mSettings.readPreferredActivitiesLPw(parser, userId);
20654                            }
20655                        }
20656                    } );
20657        } catch (Exception e) {
20658            if (DEBUG_BACKUP) {
20659                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20660            }
20661        }
20662    }
20663
20664    /**
20665     * Non-Binder method, support for the backup/restore mechanism: write the
20666     * default browser (etc) settings in its canonical XML format.  Returns the default
20667     * browser XML representation as a byte array, or null if there is none.
20668     */
20669    @Override
20670    public byte[] getDefaultAppsBackup(int userId) {
20671        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20672            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20673        }
20674
20675        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20676        try {
20677            final XmlSerializer serializer = new FastXmlSerializer();
20678            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20679            serializer.startDocument(null, true);
20680            serializer.startTag(null, TAG_DEFAULT_APPS);
20681
20682            synchronized (mPackages) {
20683                mSettings.writeDefaultAppsLPr(serializer, userId);
20684            }
20685
20686            serializer.endTag(null, TAG_DEFAULT_APPS);
20687            serializer.endDocument();
20688            serializer.flush();
20689        } catch (Exception e) {
20690            if (DEBUG_BACKUP) {
20691                Slog.e(TAG, "Unable to write default apps for backup", e);
20692            }
20693            return null;
20694        }
20695
20696        return dataStream.toByteArray();
20697    }
20698
20699    @Override
20700    public void restoreDefaultApps(byte[] backup, int userId) {
20701        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20702            throw new SecurityException("Only the system may call restoreDefaultApps()");
20703        }
20704
20705        try {
20706            final XmlPullParser parser = Xml.newPullParser();
20707            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20708            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20709                    new BlobXmlRestorer() {
20710                        @Override
20711                        public void apply(XmlPullParser parser, int userId)
20712                                throws XmlPullParserException, IOException {
20713                            synchronized (mPackages) {
20714                                mSettings.readDefaultAppsLPw(parser, userId);
20715                            }
20716                        }
20717                    } );
20718        } catch (Exception e) {
20719            if (DEBUG_BACKUP) {
20720                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20721            }
20722        }
20723    }
20724
20725    @Override
20726    public byte[] getIntentFilterVerificationBackup(int userId) {
20727        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20728            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20729        }
20730
20731        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20732        try {
20733            final XmlSerializer serializer = new FastXmlSerializer();
20734            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20735            serializer.startDocument(null, true);
20736            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20737
20738            synchronized (mPackages) {
20739                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20740            }
20741
20742            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20743            serializer.endDocument();
20744            serializer.flush();
20745        } catch (Exception e) {
20746            if (DEBUG_BACKUP) {
20747                Slog.e(TAG, "Unable to write default apps for backup", e);
20748            }
20749            return null;
20750        }
20751
20752        return dataStream.toByteArray();
20753    }
20754
20755    @Override
20756    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20757        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20758            throw new SecurityException("Only the system may call restorePreferredActivities()");
20759        }
20760
20761        try {
20762            final XmlPullParser parser = Xml.newPullParser();
20763            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20764            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20765                    new BlobXmlRestorer() {
20766                        @Override
20767                        public void apply(XmlPullParser parser, int userId)
20768                                throws XmlPullParserException, IOException {
20769                            synchronized (mPackages) {
20770                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20771                                mSettings.writeLPr();
20772                            }
20773                        }
20774                    } );
20775        } catch (Exception e) {
20776            if (DEBUG_BACKUP) {
20777                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20778            }
20779        }
20780    }
20781
20782    @Override
20783    public byte[] getPermissionGrantBackup(int userId) {
20784        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20785            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20786        }
20787
20788        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20789        try {
20790            final XmlSerializer serializer = new FastXmlSerializer();
20791            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20792            serializer.startDocument(null, true);
20793            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20794
20795            synchronized (mPackages) {
20796                serializeRuntimePermissionGrantsLPr(serializer, userId);
20797            }
20798
20799            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20800            serializer.endDocument();
20801            serializer.flush();
20802        } catch (Exception e) {
20803            if (DEBUG_BACKUP) {
20804                Slog.e(TAG, "Unable to write default apps for backup", e);
20805            }
20806            return null;
20807        }
20808
20809        return dataStream.toByteArray();
20810    }
20811
20812    @Override
20813    public void restorePermissionGrants(byte[] backup, int userId) {
20814        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20815            throw new SecurityException("Only the system may call restorePermissionGrants()");
20816        }
20817
20818        try {
20819            final XmlPullParser parser = Xml.newPullParser();
20820            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20821            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20822                    new BlobXmlRestorer() {
20823                        @Override
20824                        public void apply(XmlPullParser parser, int userId)
20825                                throws XmlPullParserException, IOException {
20826                            synchronized (mPackages) {
20827                                processRestoredPermissionGrantsLPr(parser, userId);
20828                            }
20829                        }
20830                    } );
20831        } catch (Exception e) {
20832            if (DEBUG_BACKUP) {
20833                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20834            }
20835        }
20836    }
20837
20838    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20839            throws IOException {
20840        serializer.startTag(null, TAG_ALL_GRANTS);
20841
20842        final int N = mSettings.mPackages.size();
20843        for (int i = 0; i < N; i++) {
20844            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20845            boolean pkgGrantsKnown = false;
20846
20847            PermissionsState packagePerms = ps.getPermissionsState();
20848
20849            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20850                final int grantFlags = state.getFlags();
20851                // only look at grants that are not system/policy fixed
20852                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20853                    final boolean isGranted = state.isGranted();
20854                    // And only back up the user-twiddled state bits
20855                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20856                        final String packageName = mSettings.mPackages.keyAt(i);
20857                        if (!pkgGrantsKnown) {
20858                            serializer.startTag(null, TAG_GRANT);
20859                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20860                            pkgGrantsKnown = true;
20861                        }
20862
20863                        final boolean userSet =
20864                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20865                        final boolean userFixed =
20866                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20867                        final boolean revoke =
20868                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20869
20870                        serializer.startTag(null, TAG_PERMISSION);
20871                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20872                        if (isGranted) {
20873                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20874                        }
20875                        if (userSet) {
20876                            serializer.attribute(null, ATTR_USER_SET, "true");
20877                        }
20878                        if (userFixed) {
20879                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20880                        }
20881                        if (revoke) {
20882                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20883                        }
20884                        serializer.endTag(null, TAG_PERMISSION);
20885                    }
20886                }
20887            }
20888
20889            if (pkgGrantsKnown) {
20890                serializer.endTag(null, TAG_GRANT);
20891            }
20892        }
20893
20894        serializer.endTag(null, TAG_ALL_GRANTS);
20895    }
20896
20897    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20898            throws XmlPullParserException, IOException {
20899        String pkgName = null;
20900        int outerDepth = parser.getDepth();
20901        int type;
20902        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20903                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20904            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20905                continue;
20906            }
20907
20908            final String tagName = parser.getName();
20909            if (tagName.equals(TAG_GRANT)) {
20910                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20911                if (DEBUG_BACKUP) {
20912                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20913                }
20914            } else if (tagName.equals(TAG_PERMISSION)) {
20915
20916                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20917                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20918
20919                int newFlagSet = 0;
20920                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20921                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20922                }
20923                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20924                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20925                }
20926                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20927                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20928                }
20929                if (DEBUG_BACKUP) {
20930                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
20931                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
20932                }
20933                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20934                if (ps != null) {
20935                    // Already installed so we apply the grant immediately
20936                    if (DEBUG_BACKUP) {
20937                        Slog.v(TAG, "        + already installed; applying");
20938                    }
20939                    PermissionsState perms = ps.getPermissionsState();
20940                    BasePermission bp = mSettings.mPermissions.get(permName);
20941                    if (bp != null) {
20942                        if (isGranted) {
20943                            perms.grantRuntimePermission(bp, userId);
20944                        }
20945                        if (newFlagSet != 0) {
20946                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20947                        }
20948                    }
20949                } else {
20950                    // Need to wait for post-restore install to apply the grant
20951                    if (DEBUG_BACKUP) {
20952                        Slog.v(TAG, "        - not yet installed; saving for later");
20953                    }
20954                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20955                            isGranted, newFlagSet, userId);
20956                }
20957            } else {
20958                PackageManagerService.reportSettingsProblem(Log.WARN,
20959                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20960                XmlUtils.skipCurrentTag(parser);
20961            }
20962        }
20963
20964        scheduleWriteSettingsLocked();
20965        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20966    }
20967
20968    @Override
20969    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20970            int sourceUserId, int targetUserId, int flags) {
20971        mContext.enforceCallingOrSelfPermission(
20972                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20973        int callingUid = Binder.getCallingUid();
20974        enforceOwnerRights(ownerPackage, callingUid);
20975        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20976        if (intentFilter.countActions() == 0) {
20977            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20978            return;
20979        }
20980        synchronized (mPackages) {
20981            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20982                    ownerPackage, targetUserId, flags);
20983            CrossProfileIntentResolver resolver =
20984                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20985            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20986            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20987            if (existing != null) {
20988                int size = existing.size();
20989                for (int i = 0; i < size; i++) {
20990                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20991                        return;
20992                    }
20993                }
20994            }
20995            resolver.addFilter(newFilter);
20996            scheduleWritePackageRestrictionsLocked(sourceUserId);
20997        }
20998    }
20999
21000    @Override
21001    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21002        mContext.enforceCallingOrSelfPermission(
21003                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21004        final int callingUid = Binder.getCallingUid();
21005        enforceOwnerRights(ownerPackage, callingUid);
21006        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21007        synchronized (mPackages) {
21008            CrossProfileIntentResolver resolver =
21009                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21010            ArraySet<CrossProfileIntentFilter> set =
21011                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21012            for (CrossProfileIntentFilter filter : set) {
21013                if (filter.getOwnerPackage().equals(ownerPackage)) {
21014                    resolver.removeFilter(filter);
21015                }
21016            }
21017            scheduleWritePackageRestrictionsLocked(sourceUserId);
21018        }
21019    }
21020
21021    // Enforcing that callingUid is owning pkg on userId
21022    private void enforceOwnerRights(String pkg, int callingUid) {
21023        // The system owns everything.
21024        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21025            return;
21026        }
21027        final int callingUserId = UserHandle.getUserId(callingUid);
21028        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21029        if (pi == null) {
21030            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21031                    + callingUserId);
21032        }
21033        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21034            throw new SecurityException("Calling uid " + callingUid
21035                    + " does not own package " + pkg);
21036        }
21037    }
21038
21039    @Override
21040    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21041        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21042            return null;
21043        }
21044        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21045    }
21046
21047    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21048        UserManagerService ums = UserManagerService.getInstance();
21049        if (ums != null) {
21050            final UserInfo parent = ums.getProfileParent(userId);
21051            final int launcherUid = (parent != null) ? parent.id : userId;
21052            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21053            if (launcherComponent != null) {
21054                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21055                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21056                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21057                        .setPackage(launcherComponent.getPackageName());
21058                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21059            }
21060        }
21061    }
21062
21063    /**
21064     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21065     * then reports the most likely home activity or null if there are more than one.
21066     */
21067    private ComponentName getDefaultHomeActivity(int userId) {
21068        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21069        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21070        if (cn != null) {
21071            return cn;
21072        }
21073
21074        // Find the launcher with the highest priority and return that component if there are no
21075        // other home activity with the same priority.
21076        int lastPriority = Integer.MIN_VALUE;
21077        ComponentName lastComponent = null;
21078        final int size = allHomeCandidates.size();
21079        for (int i = 0; i < size; i++) {
21080            final ResolveInfo ri = allHomeCandidates.get(i);
21081            if (ri.priority > lastPriority) {
21082                lastComponent = ri.activityInfo.getComponentName();
21083                lastPriority = ri.priority;
21084            } else if (ri.priority == lastPriority) {
21085                // Two components found with same priority.
21086                lastComponent = null;
21087            }
21088        }
21089        return lastComponent;
21090    }
21091
21092    private Intent getHomeIntent() {
21093        Intent intent = new Intent(Intent.ACTION_MAIN);
21094        intent.addCategory(Intent.CATEGORY_HOME);
21095        intent.addCategory(Intent.CATEGORY_DEFAULT);
21096        return intent;
21097    }
21098
21099    private IntentFilter getHomeFilter() {
21100        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21101        filter.addCategory(Intent.CATEGORY_HOME);
21102        filter.addCategory(Intent.CATEGORY_DEFAULT);
21103        return filter;
21104    }
21105
21106    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21107            int userId) {
21108        Intent intent  = getHomeIntent();
21109        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21110                PackageManager.GET_META_DATA, userId);
21111        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21112                true, false, false, userId);
21113
21114        allHomeCandidates.clear();
21115        if (list != null) {
21116            for (ResolveInfo ri : list) {
21117                allHomeCandidates.add(ri);
21118            }
21119        }
21120        return (preferred == null || preferred.activityInfo == null)
21121                ? null
21122                : new ComponentName(preferred.activityInfo.packageName,
21123                        preferred.activityInfo.name);
21124    }
21125
21126    @Override
21127    public void setHomeActivity(ComponentName comp, int userId) {
21128        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21129            return;
21130        }
21131        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21132        getHomeActivitiesAsUser(homeActivities, userId);
21133
21134        boolean found = false;
21135
21136        final int size = homeActivities.size();
21137        final ComponentName[] set = new ComponentName[size];
21138        for (int i = 0; i < size; i++) {
21139            final ResolveInfo candidate = homeActivities.get(i);
21140            final ActivityInfo info = candidate.activityInfo;
21141            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21142            set[i] = activityName;
21143            if (!found && activityName.equals(comp)) {
21144                found = true;
21145            }
21146        }
21147        if (!found) {
21148            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21149                    + userId);
21150        }
21151        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21152                set, comp, userId);
21153    }
21154
21155    private @Nullable String getSetupWizardPackageName() {
21156        final Intent intent = new Intent(Intent.ACTION_MAIN);
21157        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21158
21159        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21160                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21161                        | MATCH_DISABLED_COMPONENTS,
21162                UserHandle.myUserId());
21163        if (matches.size() == 1) {
21164            return matches.get(0).getComponentInfo().packageName;
21165        } else {
21166            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21167                    + ": matches=" + matches);
21168            return null;
21169        }
21170    }
21171
21172    private @Nullable String getStorageManagerPackageName() {
21173        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21174
21175        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21176                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21177                        | MATCH_DISABLED_COMPONENTS,
21178                UserHandle.myUserId());
21179        if (matches.size() == 1) {
21180            return matches.get(0).getComponentInfo().packageName;
21181        } else {
21182            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21183                    + matches.size() + ": matches=" + matches);
21184            return null;
21185        }
21186    }
21187
21188    @Override
21189    public void setApplicationEnabledSetting(String appPackageName,
21190            int newState, int flags, int userId, String callingPackage) {
21191        if (!sUserManager.exists(userId)) return;
21192        if (callingPackage == null) {
21193            callingPackage = Integer.toString(Binder.getCallingUid());
21194        }
21195        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21196    }
21197
21198    @Override
21199    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21200        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21201        synchronized (mPackages) {
21202            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21203            if (pkgSetting != null) {
21204                pkgSetting.setUpdateAvailable(updateAvailable);
21205            }
21206        }
21207    }
21208
21209    @Override
21210    public void setComponentEnabledSetting(ComponentName componentName,
21211            int newState, int flags, int userId) {
21212        if (!sUserManager.exists(userId)) return;
21213        setEnabledSetting(componentName.getPackageName(),
21214                componentName.getClassName(), newState, flags, userId, null);
21215    }
21216
21217    private void setEnabledSetting(final String packageName, String className, int newState,
21218            final int flags, int userId, String callingPackage) {
21219        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21220              || newState == COMPONENT_ENABLED_STATE_ENABLED
21221              || newState == COMPONENT_ENABLED_STATE_DISABLED
21222              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21223              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21224            throw new IllegalArgumentException("Invalid new component state: "
21225                    + newState);
21226        }
21227        PackageSetting pkgSetting;
21228        final int callingUid = Binder.getCallingUid();
21229        final int permission;
21230        if (callingUid == Process.SYSTEM_UID) {
21231            permission = PackageManager.PERMISSION_GRANTED;
21232        } else {
21233            permission = mContext.checkCallingOrSelfPermission(
21234                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21235        }
21236        enforceCrossUserPermission(callingUid, userId,
21237                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21238        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21239        boolean sendNow = false;
21240        boolean isApp = (className == null);
21241        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21242        String componentName = isApp ? packageName : className;
21243        int packageUid = -1;
21244        ArrayList<String> components;
21245
21246        // reader
21247        synchronized (mPackages) {
21248            pkgSetting = mSettings.mPackages.get(packageName);
21249            if (pkgSetting == null) {
21250                if (!isCallerInstantApp) {
21251                    if (className == null) {
21252                        throw new IllegalArgumentException("Unknown package: " + packageName);
21253                    }
21254                    throw new IllegalArgumentException(
21255                            "Unknown component: " + packageName + "/" + className);
21256                } else {
21257                    // throw SecurityException to prevent leaking package information
21258                    throw new SecurityException(
21259                            "Attempt to change component state; "
21260                            + "pid=" + Binder.getCallingPid()
21261                            + ", uid=" + callingUid
21262                            + (className == null
21263                                    ? ", package=" + packageName
21264                                    : ", component=" + packageName + "/" + className));
21265                }
21266            }
21267        }
21268
21269        // Limit who can change which apps
21270        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21271            // Don't allow apps that don't have permission to modify other apps
21272            if (!allowedByPermission
21273                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21274                throw new SecurityException(
21275                        "Attempt to change component state; "
21276                        + "pid=" + Binder.getCallingPid()
21277                        + ", uid=" + callingUid
21278                        + (className == null
21279                                ? ", package=" + packageName
21280                                : ", component=" + packageName + "/" + className));
21281            }
21282            // Don't allow changing protected packages.
21283            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21284                throw new SecurityException("Cannot disable a protected package: " + packageName);
21285            }
21286        }
21287
21288        synchronized (mPackages) {
21289            if (callingUid == Process.SHELL_UID
21290                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21291                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21292                // unless it is a test package.
21293                int oldState = pkgSetting.getEnabled(userId);
21294                if (className == null
21295                    &&
21296                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21297                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21298                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21299                    &&
21300                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21301                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
21302                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21303                    // ok
21304                } else {
21305                    throw new SecurityException(
21306                            "Shell cannot change component state for " + packageName + "/"
21307                            + className + " to " + newState);
21308                }
21309            }
21310            if (className == null) {
21311                // We're dealing with an application/package level state change
21312                if (pkgSetting.getEnabled(userId) == newState) {
21313                    // Nothing to do
21314                    return;
21315                }
21316                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21317                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21318                    // Don't care about who enables an app.
21319                    callingPackage = null;
21320                }
21321                pkgSetting.setEnabled(newState, userId, callingPackage);
21322                // pkgSetting.pkg.mSetEnabled = newState;
21323            } else {
21324                // We're dealing with a component level state change
21325                // First, verify that this is a valid class name.
21326                PackageParser.Package pkg = pkgSetting.pkg;
21327                if (pkg == null || !pkg.hasComponentClassName(className)) {
21328                    if (pkg != null &&
21329                            pkg.applicationInfo.targetSdkVersion >=
21330                                    Build.VERSION_CODES.JELLY_BEAN) {
21331                        throw new IllegalArgumentException("Component class " + className
21332                                + " does not exist in " + packageName);
21333                    } else {
21334                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21335                                + className + " does not exist in " + packageName);
21336                    }
21337                }
21338                switch (newState) {
21339                case COMPONENT_ENABLED_STATE_ENABLED:
21340                    if (!pkgSetting.enableComponentLPw(className, userId)) {
21341                        return;
21342                    }
21343                    break;
21344                case COMPONENT_ENABLED_STATE_DISABLED:
21345                    if (!pkgSetting.disableComponentLPw(className, userId)) {
21346                        return;
21347                    }
21348                    break;
21349                case COMPONENT_ENABLED_STATE_DEFAULT:
21350                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
21351                        return;
21352                    }
21353                    break;
21354                default:
21355                    Slog.e(TAG, "Invalid new component state: " + newState);
21356                    return;
21357                }
21358            }
21359            scheduleWritePackageRestrictionsLocked(userId);
21360            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21361            final long callingId = Binder.clearCallingIdentity();
21362            try {
21363                updateInstantAppInstallerLocked(packageName);
21364            } finally {
21365                Binder.restoreCallingIdentity(callingId);
21366            }
21367            components = mPendingBroadcasts.get(userId, packageName);
21368            final boolean newPackage = components == null;
21369            if (newPackage) {
21370                components = new ArrayList<String>();
21371            }
21372            if (!components.contains(componentName)) {
21373                components.add(componentName);
21374            }
21375            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21376                sendNow = true;
21377                // Purge entry from pending broadcast list if another one exists already
21378                // since we are sending one right away.
21379                mPendingBroadcasts.remove(userId, packageName);
21380            } else {
21381                if (newPackage) {
21382                    mPendingBroadcasts.put(userId, packageName, components);
21383                }
21384                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21385                    // Schedule a message
21386                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21387                }
21388            }
21389        }
21390
21391        long callingId = Binder.clearCallingIdentity();
21392        try {
21393            if (sendNow) {
21394                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21395                sendPackageChangedBroadcast(packageName,
21396                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21397            }
21398        } finally {
21399            Binder.restoreCallingIdentity(callingId);
21400        }
21401    }
21402
21403    @Override
21404    public void flushPackageRestrictionsAsUser(int userId) {
21405        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21406            return;
21407        }
21408        if (!sUserManager.exists(userId)) {
21409            return;
21410        }
21411        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21412                false /* checkShell */, "flushPackageRestrictions");
21413        synchronized (mPackages) {
21414            mSettings.writePackageRestrictionsLPr(userId);
21415            mDirtyUsers.remove(userId);
21416            if (mDirtyUsers.isEmpty()) {
21417                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21418            }
21419        }
21420    }
21421
21422    private void sendPackageChangedBroadcast(String packageName,
21423            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21424        if (DEBUG_INSTALL)
21425            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21426                    + componentNames);
21427        Bundle extras = new Bundle(4);
21428        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21429        String nameList[] = new String[componentNames.size()];
21430        componentNames.toArray(nameList);
21431        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21432        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21433        extras.putInt(Intent.EXTRA_UID, packageUid);
21434        // If this is not reporting a change of the overall package, then only send it
21435        // to registered receivers.  We don't want to launch a swath of apps for every
21436        // little component state change.
21437        final int flags = !componentNames.contains(packageName)
21438                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21439        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21440                new int[] {UserHandle.getUserId(packageUid)});
21441    }
21442
21443    @Override
21444    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21445        if (!sUserManager.exists(userId)) return;
21446        final int callingUid = Binder.getCallingUid();
21447        if (getInstantAppPackageName(callingUid) != null) {
21448            return;
21449        }
21450        final int permission = mContext.checkCallingOrSelfPermission(
21451                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21452        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21453        enforceCrossUserPermission(callingUid, userId,
21454                true /* requireFullPermission */, true /* checkShell */, "stop package");
21455        // writer
21456        synchronized (mPackages) {
21457            final PackageSetting ps = mSettings.mPackages.get(packageName);
21458            if (!filterAppAccessLPr(ps, callingUid, userId)
21459                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21460                            allowedByPermission, callingUid, userId)) {
21461                scheduleWritePackageRestrictionsLocked(userId);
21462            }
21463        }
21464    }
21465
21466    @Override
21467    public String getInstallerPackageName(String packageName) {
21468        final int callingUid = Binder.getCallingUid();
21469        if (getInstantAppPackageName(callingUid) != null) {
21470            return null;
21471        }
21472        // reader
21473        synchronized (mPackages) {
21474            final PackageSetting ps = mSettings.mPackages.get(packageName);
21475            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21476                return null;
21477            }
21478            return mSettings.getInstallerPackageNameLPr(packageName);
21479        }
21480    }
21481
21482    public boolean isOrphaned(String packageName) {
21483        // reader
21484        synchronized (mPackages) {
21485            return mSettings.isOrphaned(packageName);
21486        }
21487    }
21488
21489    @Override
21490    public int getApplicationEnabledSetting(String packageName, int userId) {
21491        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21492        int callingUid = Binder.getCallingUid();
21493        enforceCrossUserPermission(callingUid, userId,
21494                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21495        // reader
21496        synchronized (mPackages) {
21497            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21498                return COMPONENT_ENABLED_STATE_DISABLED;
21499            }
21500            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21501        }
21502    }
21503
21504    @Override
21505    public int getComponentEnabledSetting(ComponentName component, int userId) {
21506        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21507        int callingUid = Binder.getCallingUid();
21508        enforceCrossUserPermission(callingUid, userId,
21509                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21510        synchronized (mPackages) {
21511            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21512                    component, TYPE_UNKNOWN, userId)) {
21513                return COMPONENT_ENABLED_STATE_DISABLED;
21514            }
21515            return mSettings.getComponentEnabledSettingLPr(component, userId);
21516        }
21517    }
21518
21519    @Override
21520    public void enterSafeMode() {
21521        enforceSystemOrRoot("Only the system can request entering safe mode");
21522
21523        if (!mSystemReady) {
21524            mSafeMode = true;
21525        }
21526    }
21527
21528    @Override
21529    public void systemReady() {
21530        enforceSystemOrRoot("Only the system can claim the system is ready");
21531
21532        mSystemReady = true;
21533        final ContentResolver resolver = mContext.getContentResolver();
21534        ContentObserver co = new ContentObserver(mHandler) {
21535            @Override
21536            public void onChange(boolean selfChange) {
21537                mEphemeralAppsDisabled =
21538                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21539                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21540            }
21541        };
21542        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21543                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21544                false, co, UserHandle.USER_SYSTEM);
21545        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21546                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21547        co.onChange(true);
21548
21549        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21550        // disabled after already being started.
21551        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21552                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21553
21554        // Read the compatibilty setting when the system is ready.
21555        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21556                mContext.getContentResolver(),
21557                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21558        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21559        if (DEBUG_SETTINGS) {
21560            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21561        }
21562
21563        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21564
21565        synchronized (mPackages) {
21566            // Verify that all of the preferred activity components actually
21567            // exist.  It is possible for applications to be updated and at
21568            // that point remove a previously declared activity component that
21569            // had been set as a preferred activity.  We try to clean this up
21570            // the next time we encounter that preferred activity, but it is
21571            // possible for the user flow to never be able to return to that
21572            // situation so here we do a sanity check to make sure we haven't
21573            // left any junk around.
21574            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21575            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21576                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21577                removed.clear();
21578                for (PreferredActivity pa : pir.filterSet()) {
21579                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21580                        removed.add(pa);
21581                    }
21582                }
21583                if (removed.size() > 0) {
21584                    for (int r=0; r<removed.size(); r++) {
21585                        PreferredActivity pa = removed.get(r);
21586                        Slog.w(TAG, "Removing dangling preferred activity: "
21587                                + pa.mPref.mComponent);
21588                        pir.removeFilter(pa);
21589                    }
21590                    mSettings.writePackageRestrictionsLPr(
21591                            mSettings.mPreferredActivities.keyAt(i));
21592                }
21593            }
21594
21595            for (int userId : UserManagerService.getInstance().getUserIds()) {
21596                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21597                    grantPermissionsUserIds = ArrayUtils.appendInt(
21598                            grantPermissionsUserIds, userId);
21599                }
21600            }
21601        }
21602        sUserManager.systemReady();
21603
21604        // If we upgraded grant all default permissions before kicking off.
21605        for (int userId : grantPermissionsUserIds) {
21606            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21607        }
21608
21609        // If we did not grant default permissions, we preload from this the
21610        // default permission exceptions lazily to ensure we don't hit the
21611        // disk on a new user creation.
21612        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21613            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21614        }
21615
21616        // Kick off any messages waiting for system ready
21617        if (mPostSystemReadyMessages != null) {
21618            for (Message msg : mPostSystemReadyMessages) {
21619                msg.sendToTarget();
21620            }
21621            mPostSystemReadyMessages = null;
21622        }
21623
21624        // Watch for external volumes that come and go over time
21625        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21626        storage.registerListener(mStorageListener);
21627
21628        mInstallerService.systemReady();
21629        mPackageDexOptimizer.systemReady();
21630
21631        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21632                StorageManagerInternal.class);
21633        StorageManagerInternal.addExternalStoragePolicy(
21634                new StorageManagerInternal.ExternalStorageMountPolicy() {
21635            @Override
21636            public int getMountMode(int uid, String packageName) {
21637                if (Process.isIsolated(uid)) {
21638                    return Zygote.MOUNT_EXTERNAL_NONE;
21639                }
21640                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21641                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21642                }
21643                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21644                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21645                }
21646                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21647                    return Zygote.MOUNT_EXTERNAL_READ;
21648                }
21649                return Zygote.MOUNT_EXTERNAL_WRITE;
21650            }
21651
21652            @Override
21653            public boolean hasExternalStorage(int uid, String packageName) {
21654                return true;
21655            }
21656        });
21657
21658        // Now that we're mostly running, clean up stale users and apps
21659        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21660        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21661
21662        if (mPrivappPermissionsViolations != null) {
21663            Slog.wtf(TAG,"Signature|privileged permissions not in "
21664                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21665            mPrivappPermissionsViolations = null;
21666        }
21667    }
21668
21669    public void waitForAppDataPrepared() {
21670        if (mPrepareAppDataFuture == null) {
21671            return;
21672        }
21673        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21674        mPrepareAppDataFuture = null;
21675    }
21676
21677    @Override
21678    public boolean isSafeMode() {
21679        // allow instant applications
21680        return mSafeMode;
21681    }
21682
21683    @Override
21684    public boolean hasSystemUidErrors() {
21685        // allow instant applications
21686        return mHasSystemUidErrors;
21687    }
21688
21689    static String arrayToString(int[] array) {
21690        StringBuffer buf = new StringBuffer(128);
21691        buf.append('[');
21692        if (array != null) {
21693            for (int i=0; i<array.length; i++) {
21694                if (i > 0) buf.append(", ");
21695                buf.append(array[i]);
21696            }
21697        }
21698        buf.append(']');
21699        return buf.toString();
21700    }
21701
21702    static class DumpState {
21703        public static final int DUMP_LIBS = 1 << 0;
21704        public static final int DUMP_FEATURES = 1 << 1;
21705        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
21706        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
21707        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
21708        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
21709        public static final int DUMP_PERMISSIONS = 1 << 6;
21710        public static final int DUMP_PACKAGES = 1 << 7;
21711        public static final int DUMP_SHARED_USERS = 1 << 8;
21712        public static final int DUMP_MESSAGES = 1 << 9;
21713        public static final int DUMP_PROVIDERS = 1 << 10;
21714        public static final int DUMP_VERIFIERS = 1 << 11;
21715        public static final int DUMP_PREFERRED = 1 << 12;
21716        public static final int DUMP_PREFERRED_XML = 1 << 13;
21717        public static final int DUMP_KEYSETS = 1 << 14;
21718        public static final int DUMP_VERSION = 1 << 15;
21719        public static final int DUMP_INSTALLS = 1 << 16;
21720        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
21721        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
21722        public static final int DUMP_FROZEN = 1 << 19;
21723        public static final int DUMP_DEXOPT = 1 << 20;
21724        public static final int DUMP_COMPILER_STATS = 1 << 21;
21725        public static final int DUMP_CHANGES = 1 << 22;
21726        public static final int DUMP_VOLUMES = 1 << 23;
21727
21728        public static final int OPTION_SHOW_FILTERS = 1 << 0;
21729
21730        private int mTypes;
21731
21732        private int mOptions;
21733
21734        private boolean mTitlePrinted;
21735
21736        private SharedUserSetting mSharedUser;
21737
21738        public boolean isDumping(int type) {
21739            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
21740                return true;
21741            }
21742
21743            return (mTypes & type) != 0;
21744        }
21745
21746        public void setDump(int type) {
21747            mTypes |= type;
21748        }
21749
21750        public boolean isOptionEnabled(int option) {
21751            return (mOptions & option) != 0;
21752        }
21753
21754        public void setOptionEnabled(int option) {
21755            mOptions |= option;
21756        }
21757
21758        public boolean onTitlePrinted() {
21759            final boolean printed = mTitlePrinted;
21760            mTitlePrinted = true;
21761            return printed;
21762        }
21763
21764        public boolean getTitlePrinted() {
21765            return mTitlePrinted;
21766        }
21767
21768        public void setTitlePrinted(boolean enabled) {
21769            mTitlePrinted = enabled;
21770        }
21771
21772        public SharedUserSetting getSharedUser() {
21773            return mSharedUser;
21774        }
21775
21776        public void setSharedUser(SharedUserSetting user) {
21777            mSharedUser = user;
21778        }
21779    }
21780
21781    @Override
21782    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21783            FileDescriptor err, String[] args, ShellCallback callback,
21784            ResultReceiver resultReceiver) {
21785        (new PackageManagerShellCommand(this)).exec(
21786                this, in, out, err, args, callback, resultReceiver);
21787    }
21788
21789    @Override
21790    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21791        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21792
21793        DumpState dumpState = new DumpState();
21794        boolean fullPreferred = false;
21795        boolean checkin = false;
21796
21797        String packageName = null;
21798        ArraySet<String> permissionNames = null;
21799
21800        int opti = 0;
21801        while (opti < args.length) {
21802            String opt = args[opti];
21803            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21804                break;
21805            }
21806            opti++;
21807
21808            if ("-a".equals(opt)) {
21809                // Right now we only know how to print all.
21810            } else if ("-h".equals(opt)) {
21811                pw.println("Package manager dump options:");
21812                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21813                pw.println("    --checkin: dump for a checkin");
21814                pw.println("    -f: print details of intent filters");
21815                pw.println("    -h: print this help");
21816                pw.println("  cmd may be one of:");
21817                pw.println("    l[ibraries]: list known shared libraries");
21818                pw.println("    f[eatures]: list device features");
21819                pw.println("    k[eysets]: print known keysets");
21820                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21821                pw.println("    perm[issions]: dump permissions");
21822                pw.println("    permission [name ...]: dump declaration and use of given permission");
21823                pw.println("    pref[erred]: print preferred package settings");
21824                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21825                pw.println("    prov[iders]: dump content providers");
21826                pw.println("    p[ackages]: dump installed packages");
21827                pw.println("    s[hared-users]: dump shared user IDs");
21828                pw.println("    m[essages]: print collected runtime messages");
21829                pw.println("    v[erifiers]: print package verifier info");
21830                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21831                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21832                pw.println("    version: print database version info");
21833                pw.println("    write: write current settings now");
21834                pw.println("    installs: details about install sessions");
21835                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21836                pw.println("    dexopt: dump dexopt state");
21837                pw.println("    compiler-stats: dump compiler statistics");
21838                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21839                pw.println("    <package.name>: info about given package");
21840                return;
21841            } else if ("--checkin".equals(opt)) {
21842                checkin = true;
21843            } else if ("-f".equals(opt)) {
21844                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21845            } else if ("--proto".equals(opt)) {
21846                dumpProto(fd);
21847                return;
21848            } else {
21849                pw.println("Unknown argument: " + opt + "; use -h for help");
21850            }
21851        }
21852
21853        // Is the caller requesting to dump a particular piece of data?
21854        if (opti < args.length) {
21855            String cmd = args[opti];
21856            opti++;
21857            // Is this a package name?
21858            if ("android".equals(cmd) || cmd.contains(".")) {
21859                packageName = cmd;
21860                // When dumping a single package, we always dump all of its
21861                // filter information since the amount of data will be reasonable.
21862                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21863            } else if ("check-permission".equals(cmd)) {
21864                if (opti >= args.length) {
21865                    pw.println("Error: check-permission missing permission argument");
21866                    return;
21867                }
21868                String perm = args[opti];
21869                opti++;
21870                if (opti >= args.length) {
21871                    pw.println("Error: check-permission missing package argument");
21872                    return;
21873                }
21874
21875                String pkg = args[opti];
21876                opti++;
21877                int user = UserHandle.getUserId(Binder.getCallingUid());
21878                if (opti < args.length) {
21879                    try {
21880                        user = Integer.parseInt(args[opti]);
21881                    } catch (NumberFormatException e) {
21882                        pw.println("Error: check-permission user argument is not a number: "
21883                                + args[opti]);
21884                        return;
21885                    }
21886                }
21887
21888                // Normalize package name to handle renamed packages and static libs
21889                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21890
21891                pw.println(checkPermission(perm, pkg, user));
21892                return;
21893            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21894                dumpState.setDump(DumpState.DUMP_LIBS);
21895            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21896                dumpState.setDump(DumpState.DUMP_FEATURES);
21897            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21898                if (opti >= args.length) {
21899                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21900                            | DumpState.DUMP_SERVICE_RESOLVERS
21901                            | DumpState.DUMP_RECEIVER_RESOLVERS
21902                            | DumpState.DUMP_CONTENT_RESOLVERS);
21903                } else {
21904                    while (opti < args.length) {
21905                        String name = args[opti];
21906                        if ("a".equals(name) || "activity".equals(name)) {
21907                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21908                        } else if ("s".equals(name) || "service".equals(name)) {
21909                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21910                        } else if ("r".equals(name) || "receiver".equals(name)) {
21911                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21912                        } else if ("c".equals(name) || "content".equals(name)) {
21913                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21914                        } else {
21915                            pw.println("Error: unknown resolver table type: " + name);
21916                            return;
21917                        }
21918                        opti++;
21919                    }
21920                }
21921            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21922                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21923            } else if ("permission".equals(cmd)) {
21924                if (opti >= args.length) {
21925                    pw.println("Error: permission requires permission name");
21926                    return;
21927                }
21928                permissionNames = new ArraySet<>();
21929                while (opti < args.length) {
21930                    permissionNames.add(args[opti]);
21931                    opti++;
21932                }
21933                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21934                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21935            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21936                dumpState.setDump(DumpState.DUMP_PREFERRED);
21937            } else if ("preferred-xml".equals(cmd)) {
21938                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21939                if (opti < args.length && "--full".equals(args[opti])) {
21940                    fullPreferred = true;
21941                    opti++;
21942                }
21943            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21944                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21945            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21946                dumpState.setDump(DumpState.DUMP_PACKAGES);
21947            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21948                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21949            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21950                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21951            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21952                dumpState.setDump(DumpState.DUMP_MESSAGES);
21953            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21954                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21955            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21956                    || "intent-filter-verifiers".equals(cmd)) {
21957                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21958            } else if ("version".equals(cmd)) {
21959                dumpState.setDump(DumpState.DUMP_VERSION);
21960            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21961                dumpState.setDump(DumpState.DUMP_KEYSETS);
21962            } else if ("installs".equals(cmd)) {
21963                dumpState.setDump(DumpState.DUMP_INSTALLS);
21964            } else if ("frozen".equals(cmd)) {
21965                dumpState.setDump(DumpState.DUMP_FROZEN);
21966            } else if ("volumes".equals(cmd)) {
21967                dumpState.setDump(DumpState.DUMP_VOLUMES);
21968            } else if ("dexopt".equals(cmd)) {
21969                dumpState.setDump(DumpState.DUMP_DEXOPT);
21970            } else if ("compiler-stats".equals(cmd)) {
21971                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21972            } else if ("changes".equals(cmd)) {
21973                dumpState.setDump(DumpState.DUMP_CHANGES);
21974            } else if ("write".equals(cmd)) {
21975                synchronized (mPackages) {
21976                    mSettings.writeLPr();
21977                    pw.println("Settings written.");
21978                    return;
21979                }
21980            }
21981        }
21982
21983        if (checkin) {
21984            pw.println("vers,1");
21985        }
21986
21987        // reader
21988        synchronized (mPackages) {
21989            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21990                if (!checkin) {
21991                    if (dumpState.onTitlePrinted())
21992                        pw.println();
21993                    pw.println("Database versions:");
21994                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21995                }
21996            }
21997
21998            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21999                if (!checkin) {
22000                    if (dumpState.onTitlePrinted())
22001                        pw.println();
22002                    pw.println("Verifiers:");
22003                    pw.print("  Required: ");
22004                    pw.print(mRequiredVerifierPackage);
22005                    pw.print(" (uid=");
22006                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22007                            UserHandle.USER_SYSTEM));
22008                    pw.println(")");
22009                } else if (mRequiredVerifierPackage != null) {
22010                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22011                    pw.print(",");
22012                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22013                            UserHandle.USER_SYSTEM));
22014                }
22015            }
22016
22017            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22018                    packageName == null) {
22019                if (mIntentFilterVerifierComponent != null) {
22020                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22021                    if (!checkin) {
22022                        if (dumpState.onTitlePrinted())
22023                            pw.println();
22024                        pw.println("Intent Filter Verifier:");
22025                        pw.print("  Using: ");
22026                        pw.print(verifierPackageName);
22027                        pw.print(" (uid=");
22028                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22029                                UserHandle.USER_SYSTEM));
22030                        pw.println(")");
22031                    } else if (verifierPackageName != null) {
22032                        pw.print("ifv,"); pw.print(verifierPackageName);
22033                        pw.print(",");
22034                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22035                                UserHandle.USER_SYSTEM));
22036                    }
22037                } else {
22038                    pw.println();
22039                    pw.println("No Intent Filter Verifier available!");
22040                }
22041            }
22042
22043            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22044                boolean printedHeader = false;
22045                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22046                while (it.hasNext()) {
22047                    String libName = it.next();
22048                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22049                    if (versionedLib == null) {
22050                        continue;
22051                    }
22052                    final int versionCount = versionedLib.size();
22053                    for (int i = 0; i < versionCount; i++) {
22054                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22055                        if (!checkin) {
22056                            if (!printedHeader) {
22057                                if (dumpState.onTitlePrinted())
22058                                    pw.println();
22059                                pw.println("Libraries:");
22060                                printedHeader = true;
22061                            }
22062                            pw.print("  ");
22063                        } else {
22064                            pw.print("lib,");
22065                        }
22066                        pw.print(libEntry.info.getName());
22067                        if (libEntry.info.isStatic()) {
22068                            pw.print(" version=" + libEntry.info.getVersion());
22069                        }
22070                        if (!checkin) {
22071                            pw.print(" -> ");
22072                        }
22073                        if (libEntry.path != null) {
22074                            pw.print(" (jar) ");
22075                            pw.print(libEntry.path);
22076                        } else {
22077                            pw.print(" (apk) ");
22078                            pw.print(libEntry.apk);
22079                        }
22080                        pw.println();
22081                    }
22082                }
22083            }
22084
22085            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22086                if (dumpState.onTitlePrinted())
22087                    pw.println();
22088                if (!checkin) {
22089                    pw.println("Features:");
22090                }
22091
22092                synchronized (mAvailableFeatures) {
22093                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22094                        if (checkin) {
22095                            pw.print("feat,");
22096                            pw.print(feat.name);
22097                            pw.print(",");
22098                            pw.println(feat.version);
22099                        } else {
22100                            pw.print("  ");
22101                            pw.print(feat.name);
22102                            if (feat.version > 0) {
22103                                pw.print(" version=");
22104                                pw.print(feat.version);
22105                            }
22106                            pw.println();
22107                        }
22108                    }
22109                }
22110            }
22111
22112            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22113                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22114                        : "Activity Resolver Table:", "  ", packageName,
22115                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22116                    dumpState.setTitlePrinted(true);
22117                }
22118            }
22119            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22120                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22121                        : "Receiver Resolver Table:", "  ", packageName,
22122                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22123                    dumpState.setTitlePrinted(true);
22124                }
22125            }
22126            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22127                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22128                        : "Service Resolver Table:", "  ", packageName,
22129                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22130                    dumpState.setTitlePrinted(true);
22131                }
22132            }
22133            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22134                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22135                        : "Provider Resolver Table:", "  ", packageName,
22136                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22137                    dumpState.setTitlePrinted(true);
22138                }
22139            }
22140
22141            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22142                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22143                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22144                    int user = mSettings.mPreferredActivities.keyAt(i);
22145                    if (pir.dump(pw,
22146                            dumpState.getTitlePrinted()
22147                                ? "\nPreferred Activities User " + user + ":"
22148                                : "Preferred Activities User " + user + ":", "  ",
22149                            packageName, true, false)) {
22150                        dumpState.setTitlePrinted(true);
22151                    }
22152                }
22153            }
22154
22155            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22156                pw.flush();
22157                FileOutputStream fout = new FileOutputStream(fd);
22158                BufferedOutputStream str = new BufferedOutputStream(fout);
22159                XmlSerializer serializer = new FastXmlSerializer();
22160                try {
22161                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22162                    serializer.startDocument(null, true);
22163                    serializer.setFeature(
22164                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22165                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22166                    serializer.endDocument();
22167                    serializer.flush();
22168                } catch (IllegalArgumentException e) {
22169                    pw.println("Failed writing: " + e);
22170                } catch (IllegalStateException e) {
22171                    pw.println("Failed writing: " + e);
22172                } catch (IOException e) {
22173                    pw.println("Failed writing: " + e);
22174                }
22175            }
22176
22177            if (!checkin
22178                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22179                    && packageName == null) {
22180                pw.println();
22181                int count = mSettings.mPackages.size();
22182                if (count == 0) {
22183                    pw.println("No applications!");
22184                    pw.println();
22185                } else {
22186                    final String prefix = "  ";
22187                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22188                    if (allPackageSettings.size() == 0) {
22189                        pw.println("No domain preferred apps!");
22190                        pw.println();
22191                    } else {
22192                        pw.println("App verification status:");
22193                        pw.println();
22194                        count = 0;
22195                        for (PackageSetting ps : allPackageSettings) {
22196                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22197                            if (ivi == null || ivi.getPackageName() == null) continue;
22198                            pw.println(prefix + "Package: " + ivi.getPackageName());
22199                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22200                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22201                            pw.println();
22202                            count++;
22203                        }
22204                        if (count == 0) {
22205                            pw.println(prefix + "No app verification established.");
22206                            pw.println();
22207                        }
22208                        for (int userId : sUserManager.getUserIds()) {
22209                            pw.println("App linkages for user " + userId + ":");
22210                            pw.println();
22211                            count = 0;
22212                            for (PackageSetting ps : allPackageSettings) {
22213                                final long status = ps.getDomainVerificationStatusForUser(userId);
22214                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22215                                        && !DEBUG_DOMAIN_VERIFICATION) {
22216                                    continue;
22217                                }
22218                                pw.println(prefix + "Package: " + ps.name);
22219                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22220                                String statusStr = IntentFilterVerificationInfo.
22221                                        getStatusStringFromValue(status);
22222                                pw.println(prefix + "Status:  " + statusStr);
22223                                pw.println();
22224                                count++;
22225                            }
22226                            if (count == 0) {
22227                                pw.println(prefix + "No configured app linkages.");
22228                                pw.println();
22229                            }
22230                        }
22231                    }
22232                }
22233            }
22234
22235            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22236                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22237                if (packageName == null && permissionNames == null) {
22238                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22239                        if (iperm == 0) {
22240                            if (dumpState.onTitlePrinted())
22241                                pw.println();
22242                            pw.println("AppOp Permissions:");
22243                        }
22244                        pw.print("  AppOp Permission ");
22245                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22246                        pw.println(":");
22247                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22248                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22249                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22250                        }
22251                    }
22252                }
22253            }
22254
22255            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22256                boolean printedSomething = false;
22257                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22258                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22259                        continue;
22260                    }
22261                    if (!printedSomething) {
22262                        if (dumpState.onTitlePrinted())
22263                            pw.println();
22264                        pw.println("Registered ContentProviders:");
22265                        printedSomething = true;
22266                    }
22267                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22268                    pw.print("    "); pw.println(p.toString());
22269                }
22270                printedSomething = false;
22271                for (Map.Entry<String, PackageParser.Provider> entry :
22272                        mProvidersByAuthority.entrySet()) {
22273                    PackageParser.Provider p = entry.getValue();
22274                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22275                        continue;
22276                    }
22277                    if (!printedSomething) {
22278                        if (dumpState.onTitlePrinted())
22279                            pw.println();
22280                        pw.println("ContentProvider Authorities:");
22281                        printedSomething = true;
22282                    }
22283                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22284                    pw.print("    "); pw.println(p.toString());
22285                    if (p.info != null && p.info.applicationInfo != null) {
22286                        final String appInfo = p.info.applicationInfo.toString();
22287                        pw.print("      applicationInfo="); pw.println(appInfo);
22288                    }
22289                }
22290            }
22291
22292            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22293                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22294            }
22295
22296            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22297                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22298            }
22299
22300            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22301                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22302            }
22303
22304            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22305                if (dumpState.onTitlePrinted()) pw.println();
22306                pw.println("Package Changes:");
22307                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22308                final int K = mChangedPackages.size();
22309                for (int i = 0; i < K; i++) {
22310                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22311                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22312                    final int N = changes.size();
22313                    if (N == 0) {
22314                        pw.print("    "); pw.println("No packages changed");
22315                    } else {
22316                        for (int j = 0; j < N; j++) {
22317                            final String pkgName = changes.valueAt(j);
22318                            final int sequenceNumber = changes.keyAt(j);
22319                            pw.print("    ");
22320                            pw.print("seq=");
22321                            pw.print(sequenceNumber);
22322                            pw.print(", package=");
22323                            pw.println(pkgName);
22324                        }
22325                    }
22326                }
22327            }
22328
22329            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22330                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22331            }
22332
22333            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22334                // XXX should handle packageName != null by dumping only install data that
22335                // the given package is involved with.
22336                if (dumpState.onTitlePrinted()) pw.println();
22337
22338                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22339                ipw.println();
22340                ipw.println("Frozen packages:");
22341                ipw.increaseIndent();
22342                if (mFrozenPackages.size() == 0) {
22343                    ipw.println("(none)");
22344                } else {
22345                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22346                        ipw.println(mFrozenPackages.valueAt(i));
22347                    }
22348                }
22349                ipw.decreaseIndent();
22350            }
22351
22352            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
22353                if (dumpState.onTitlePrinted()) pw.println();
22354
22355                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22356                ipw.println();
22357                ipw.println("Loaded volumes:");
22358                ipw.increaseIndent();
22359                if (mLoadedVolumes.size() == 0) {
22360                    ipw.println("(none)");
22361                } else {
22362                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
22363                        ipw.println(mLoadedVolumes.valueAt(i));
22364                    }
22365                }
22366                ipw.decreaseIndent();
22367            }
22368
22369            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22370                if (dumpState.onTitlePrinted()) pw.println();
22371                dumpDexoptStateLPr(pw, packageName);
22372            }
22373
22374            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22375                if (dumpState.onTitlePrinted()) pw.println();
22376                dumpCompilerStatsLPr(pw, packageName);
22377            }
22378
22379            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22380                if (dumpState.onTitlePrinted()) pw.println();
22381                mSettings.dumpReadMessagesLPr(pw, dumpState);
22382
22383                pw.println();
22384                pw.println("Package warning messages:");
22385                BufferedReader in = null;
22386                String line = null;
22387                try {
22388                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22389                    while ((line = in.readLine()) != null) {
22390                        if (line.contains("ignored: updated version")) continue;
22391                        pw.println(line);
22392                    }
22393                } catch (IOException ignored) {
22394                } finally {
22395                    IoUtils.closeQuietly(in);
22396                }
22397            }
22398
22399            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22400                BufferedReader in = null;
22401                String line = null;
22402                try {
22403                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22404                    while ((line = in.readLine()) != null) {
22405                        if (line.contains("ignored: updated version")) continue;
22406                        pw.print("msg,");
22407                        pw.println(line);
22408                    }
22409                } catch (IOException ignored) {
22410                } finally {
22411                    IoUtils.closeQuietly(in);
22412                }
22413            }
22414        }
22415
22416        // PackageInstaller should be called outside of mPackages lock
22417        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22418            // XXX should handle packageName != null by dumping only install data that
22419            // the given package is involved with.
22420            if (dumpState.onTitlePrinted()) pw.println();
22421            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22422        }
22423    }
22424
22425    private void dumpProto(FileDescriptor fd) {
22426        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22427
22428        synchronized (mPackages) {
22429            final long requiredVerifierPackageToken =
22430                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22431            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22432            proto.write(
22433                    PackageServiceDumpProto.PackageShortProto.UID,
22434                    getPackageUid(
22435                            mRequiredVerifierPackage,
22436                            MATCH_DEBUG_TRIAGED_MISSING,
22437                            UserHandle.USER_SYSTEM));
22438            proto.end(requiredVerifierPackageToken);
22439
22440            if (mIntentFilterVerifierComponent != null) {
22441                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22442                final long verifierPackageToken =
22443                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22444                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22445                proto.write(
22446                        PackageServiceDumpProto.PackageShortProto.UID,
22447                        getPackageUid(
22448                                verifierPackageName,
22449                                MATCH_DEBUG_TRIAGED_MISSING,
22450                                UserHandle.USER_SYSTEM));
22451                proto.end(verifierPackageToken);
22452            }
22453
22454            dumpSharedLibrariesProto(proto);
22455            dumpFeaturesProto(proto);
22456            mSettings.dumpPackagesProto(proto);
22457            mSettings.dumpSharedUsersProto(proto);
22458            dumpMessagesProto(proto);
22459        }
22460        proto.flush();
22461    }
22462
22463    private void dumpMessagesProto(ProtoOutputStream proto) {
22464        BufferedReader in = null;
22465        String line = null;
22466        try {
22467            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22468            while ((line = in.readLine()) != null) {
22469                if (line.contains("ignored: updated version")) continue;
22470                proto.write(PackageServiceDumpProto.MESSAGES, line);
22471            }
22472        } catch (IOException ignored) {
22473        } finally {
22474            IoUtils.closeQuietly(in);
22475        }
22476    }
22477
22478    private void dumpFeaturesProto(ProtoOutputStream proto) {
22479        synchronized (mAvailableFeatures) {
22480            final int count = mAvailableFeatures.size();
22481            for (int i = 0; i < count; i++) {
22482                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22483                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22484                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22485                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22486                proto.end(featureToken);
22487            }
22488        }
22489    }
22490
22491    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22492        final int count = mSharedLibraries.size();
22493        for (int i = 0; i < count; i++) {
22494            final String libName = mSharedLibraries.keyAt(i);
22495            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22496            if (versionedLib == null) {
22497                continue;
22498            }
22499            final int versionCount = versionedLib.size();
22500            for (int j = 0; j < versionCount; j++) {
22501                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22502                final long sharedLibraryToken =
22503                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22504                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22505                final boolean isJar = (libEntry.path != null);
22506                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22507                if (isJar) {
22508                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22509                } else {
22510                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22511                }
22512                proto.end(sharedLibraryToken);
22513            }
22514        }
22515    }
22516
22517    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22518        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22519        ipw.println();
22520        ipw.println("Dexopt state:");
22521        ipw.increaseIndent();
22522        Collection<PackageParser.Package> packages = null;
22523        if (packageName != null) {
22524            PackageParser.Package targetPackage = mPackages.get(packageName);
22525            if (targetPackage != null) {
22526                packages = Collections.singletonList(targetPackage);
22527            } else {
22528                ipw.println("Unable to find package: " + packageName);
22529                return;
22530            }
22531        } else {
22532            packages = mPackages.values();
22533        }
22534
22535        for (PackageParser.Package pkg : packages) {
22536            ipw.println("[" + pkg.packageName + "]");
22537            ipw.increaseIndent();
22538            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
22539            ipw.decreaseIndent();
22540        }
22541    }
22542
22543    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22544        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22545        ipw.println();
22546        ipw.println("Compiler stats:");
22547        ipw.increaseIndent();
22548        Collection<PackageParser.Package> packages = null;
22549        if (packageName != null) {
22550            PackageParser.Package targetPackage = mPackages.get(packageName);
22551            if (targetPackage != null) {
22552                packages = Collections.singletonList(targetPackage);
22553            } else {
22554                ipw.println("Unable to find package: " + packageName);
22555                return;
22556            }
22557        } else {
22558            packages = mPackages.values();
22559        }
22560
22561        for (PackageParser.Package pkg : packages) {
22562            ipw.println("[" + pkg.packageName + "]");
22563            ipw.increaseIndent();
22564
22565            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22566            if (stats == null) {
22567                ipw.println("(No recorded stats)");
22568            } else {
22569                stats.dump(ipw);
22570            }
22571            ipw.decreaseIndent();
22572        }
22573    }
22574
22575    private String dumpDomainString(String packageName) {
22576        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22577                .getList();
22578        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22579
22580        ArraySet<String> result = new ArraySet<>();
22581        if (iviList.size() > 0) {
22582            for (IntentFilterVerificationInfo ivi : iviList) {
22583                for (String host : ivi.getDomains()) {
22584                    result.add(host);
22585                }
22586            }
22587        }
22588        if (filters != null && filters.size() > 0) {
22589            for (IntentFilter filter : filters) {
22590                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22591                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22592                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22593                    result.addAll(filter.getHostsList());
22594                }
22595            }
22596        }
22597
22598        StringBuilder sb = new StringBuilder(result.size() * 16);
22599        for (String domain : result) {
22600            if (sb.length() > 0) sb.append(" ");
22601            sb.append(domain);
22602        }
22603        return sb.toString();
22604    }
22605
22606    // ------- apps on sdcard specific code -------
22607    static final boolean DEBUG_SD_INSTALL = false;
22608
22609    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22610
22611    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22612
22613    private boolean mMediaMounted = false;
22614
22615    static String getEncryptKey() {
22616        try {
22617            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22618                    SD_ENCRYPTION_KEYSTORE_NAME);
22619            if (sdEncKey == null) {
22620                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22621                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22622                if (sdEncKey == null) {
22623                    Slog.e(TAG, "Failed to create encryption keys");
22624                    return null;
22625                }
22626            }
22627            return sdEncKey;
22628        } catch (NoSuchAlgorithmException nsae) {
22629            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22630            return null;
22631        } catch (IOException ioe) {
22632            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22633            return null;
22634        }
22635    }
22636
22637    /*
22638     * Update media status on PackageManager.
22639     */
22640    @Override
22641    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
22642        enforceSystemOrRoot("Media status can only be updated by the system");
22643        // reader; this apparently protects mMediaMounted, but should probably
22644        // be a different lock in that case.
22645        synchronized (mPackages) {
22646            Log.i(TAG, "Updating external media status from "
22647                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
22648                    + (mediaStatus ? "mounted" : "unmounted"));
22649            if (DEBUG_SD_INSTALL)
22650                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
22651                        + ", mMediaMounted=" + mMediaMounted);
22652            if (mediaStatus == mMediaMounted) {
22653                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
22654                        : 0, -1);
22655                mHandler.sendMessage(msg);
22656                return;
22657            }
22658            mMediaMounted = mediaStatus;
22659        }
22660        // Queue up an async operation since the package installation may take a
22661        // little while.
22662        mHandler.post(new Runnable() {
22663            public void run() {
22664                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
22665            }
22666        });
22667    }
22668
22669    /**
22670     * Called by StorageManagerService when the initial ASECs to scan are available.
22671     * Should block until all the ASEC containers are finished being scanned.
22672     */
22673    public void scanAvailableAsecs() {
22674        updateExternalMediaStatusInner(true, false, false);
22675    }
22676
22677    /*
22678     * Collect information of applications on external media, map them against
22679     * existing containers and update information based on current mount status.
22680     * Please note that we always have to report status if reportStatus has been
22681     * set to true especially when unloading packages.
22682     */
22683    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
22684            boolean externalStorage) {
22685        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
22686        int[] uidArr = EmptyArray.INT;
22687
22688        final String[] list = PackageHelper.getSecureContainerList();
22689        if (ArrayUtils.isEmpty(list)) {
22690            Log.i(TAG, "No secure containers found");
22691        } else {
22692            // Process list of secure containers and categorize them
22693            // as active or stale based on their package internal state.
22694
22695            // reader
22696            synchronized (mPackages) {
22697                for (String cid : list) {
22698                    // Leave stages untouched for now; installer service owns them
22699                    if (PackageInstallerService.isStageName(cid)) continue;
22700
22701                    if (DEBUG_SD_INSTALL)
22702                        Log.i(TAG, "Processing container " + cid);
22703                    String pkgName = getAsecPackageName(cid);
22704                    if (pkgName == null) {
22705                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
22706                        continue;
22707                    }
22708                    if (DEBUG_SD_INSTALL)
22709                        Log.i(TAG, "Looking for pkg : " + pkgName);
22710
22711                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
22712                    if (ps == null) {
22713                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
22714                        continue;
22715                    }
22716
22717                    /*
22718                     * Skip packages that are not external if we're unmounting
22719                     * external storage.
22720                     */
22721                    if (externalStorage && !isMounted && !isExternal(ps)) {
22722                        continue;
22723                    }
22724
22725                    final AsecInstallArgs args = new AsecInstallArgs(cid,
22726                            getAppDexInstructionSets(ps), ps.isForwardLocked());
22727                    // The package status is changed only if the code path
22728                    // matches between settings and the container id.
22729                    if (ps.codePathString != null
22730                            && ps.codePathString.startsWith(args.getCodePath())) {
22731                        if (DEBUG_SD_INSTALL) {
22732                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
22733                                    + " at code path: " + ps.codePathString);
22734                        }
22735
22736                        // We do have a valid package installed on sdcard
22737                        processCids.put(args, ps.codePathString);
22738                        final int uid = ps.appId;
22739                        if (uid != -1) {
22740                            uidArr = ArrayUtils.appendInt(uidArr, uid);
22741                        }
22742                    } else {
22743                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
22744                                + ps.codePathString);
22745                    }
22746                }
22747            }
22748
22749            Arrays.sort(uidArr);
22750        }
22751
22752        // Process packages with valid entries.
22753        if (isMounted) {
22754            if (DEBUG_SD_INSTALL)
22755                Log.i(TAG, "Loading packages");
22756            loadMediaPackages(processCids, uidArr, externalStorage);
22757            startCleaningPackages();
22758            mInstallerService.onSecureContainersAvailable();
22759        } else {
22760            if (DEBUG_SD_INSTALL)
22761                Log.i(TAG, "Unloading packages");
22762            unloadMediaPackages(processCids, uidArr, reportStatus);
22763        }
22764    }
22765
22766    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22767            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22768        final int size = infos.size();
22769        final String[] packageNames = new String[size];
22770        final int[] packageUids = new int[size];
22771        for (int i = 0; i < size; i++) {
22772            final ApplicationInfo info = infos.get(i);
22773            packageNames[i] = info.packageName;
22774            packageUids[i] = info.uid;
22775        }
22776        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22777                finishedReceiver);
22778    }
22779
22780    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22781            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22782        sendResourcesChangedBroadcast(mediaStatus, replacing,
22783                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22784    }
22785
22786    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22787            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22788        int size = pkgList.length;
22789        if (size > 0) {
22790            // Send broadcasts here
22791            Bundle extras = new Bundle();
22792            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22793            if (uidArr != null) {
22794                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22795            }
22796            if (replacing) {
22797                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22798            }
22799            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22800                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22801            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
22802        }
22803    }
22804
22805   /*
22806     * Look at potentially valid container ids from processCids If package
22807     * information doesn't match the one on record or package scanning fails,
22808     * the cid is added to list of removeCids. We currently don't delete stale
22809     * containers.
22810     */
22811    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
22812            boolean externalStorage) {
22813        ArrayList<String> pkgList = new ArrayList<String>();
22814        Set<AsecInstallArgs> keys = processCids.keySet();
22815
22816        for (AsecInstallArgs args : keys) {
22817            String codePath = processCids.get(args);
22818            if (DEBUG_SD_INSTALL)
22819                Log.i(TAG, "Loading container : " + args.cid);
22820            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
22821            try {
22822                // Make sure there are no container errors first.
22823                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
22824                    Slog.e(TAG, "Failed to mount cid : " + args.cid
22825                            + " when installing from sdcard");
22826                    continue;
22827                }
22828                // Check code path here.
22829                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
22830                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
22831                            + " does not match one in settings " + codePath);
22832                    continue;
22833                }
22834                // Parse package
22835                int parseFlags = mDefParseFlags;
22836                if (args.isExternalAsec()) {
22837                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
22838                }
22839                if (args.isFwdLocked()) {
22840                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
22841                }
22842
22843                synchronized (mInstallLock) {
22844                    PackageParser.Package pkg = null;
22845                    try {
22846                        // Sadly we don't know the package name yet to freeze it
22847                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
22848                                SCAN_IGNORE_FROZEN, 0, null);
22849                    } catch (PackageManagerException e) {
22850                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
22851                    }
22852                    // Scan the package
22853                    if (pkg != null) {
22854                        /*
22855                         * TODO why is the lock being held? doPostInstall is
22856                         * called in other places without the lock. This needs
22857                         * to be straightened out.
22858                         */
22859                        // writer
22860                        synchronized (mPackages) {
22861                            retCode = PackageManager.INSTALL_SUCCEEDED;
22862                            pkgList.add(pkg.packageName);
22863                            // Post process args
22864                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
22865                                    pkg.applicationInfo.uid);
22866                        }
22867                    } else {
22868                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
22869                    }
22870                }
22871
22872            } finally {
22873                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
22874                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
22875                }
22876            }
22877        }
22878        // writer
22879        synchronized (mPackages) {
22880            // If the platform SDK has changed since the last time we booted,
22881            // we need to re-grant app permission to catch any new ones that
22882            // appear. This is really a hack, and means that apps can in some
22883            // cases get permissions that the user didn't initially explicitly
22884            // allow... it would be nice to have some better way to handle
22885            // this situation.
22886            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
22887                    : mSettings.getInternalVersion();
22888            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
22889                    : StorageManager.UUID_PRIVATE_INTERNAL;
22890
22891            int updateFlags = UPDATE_PERMISSIONS_ALL;
22892            if (ver.sdkVersion != mSdkVersion) {
22893                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22894                        + mSdkVersion + "; regranting permissions for external");
22895                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22896            }
22897            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22898
22899            // Yay, everything is now upgraded
22900            ver.forceCurrent();
22901
22902            // can downgrade to reader
22903            // Persist settings
22904            mSettings.writeLPr();
22905        }
22906        // Send a broadcast to let everyone know we are done processing
22907        if (pkgList.size() > 0) {
22908            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
22909        }
22910    }
22911
22912   /*
22913     * Utility method to unload a list of specified containers
22914     */
22915    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
22916        // Just unmount all valid containers.
22917        for (AsecInstallArgs arg : cidArgs) {
22918            synchronized (mInstallLock) {
22919                arg.doPostDeleteLI(false);
22920           }
22921       }
22922   }
22923
22924    /*
22925     * Unload packages mounted on external media. This involves deleting package
22926     * data from internal structures, sending broadcasts about disabled packages,
22927     * gc'ing to free up references, unmounting all secure containers
22928     * corresponding to packages on external media, and posting a
22929     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
22930     * that we always have to post this message if status has been requested no
22931     * matter what.
22932     */
22933    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
22934            final boolean reportStatus) {
22935        if (DEBUG_SD_INSTALL)
22936            Log.i(TAG, "unloading media packages");
22937        ArrayList<String> pkgList = new ArrayList<String>();
22938        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
22939        final Set<AsecInstallArgs> keys = processCids.keySet();
22940        for (AsecInstallArgs args : keys) {
22941            String pkgName = args.getPackageName();
22942            if (DEBUG_SD_INSTALL)
22943                Log.i(TAG, "Trying to unload pkg : " + pkgName);
22944            // Delete package internally
22945            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22946            synchronized (mInstallLock) {
22947                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22948                final boolean res;
22949                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
22950                        "unloadMediaPackages")) {
22951                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
22952                            null);
22953                }
22954                if (res) {
22955                    pkgList.add(pkgName);
22956                } else {
22957                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
22958                    failedList.add(args);
22959                }
22960            }
22961        }
22962
22963        // reader
22964        synchronized (mPackages) {
22965            // We didn't update the settings after removing each package;
22966            // write them now for all packages.
22967            mSettings.writeLPr();
22968        }
22969
22970        // We have to absolutely send UPDATED_MEDIA_STATUS only
22971        // after confirming that all the receivers processed the ordered
22972        // broadcast when packages get disabled, force a gc to clean things up.
22973        // and unload all the containers.
22974        if (pkgList.size() > 0) {
22975            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
22976                    new IIntentReceiver.Stub() {
22977                public void performReceive(Intent intent, int resultCode, String data,
22978                        Bundle extras, boolean ordered, boolean sticky,
22979                        int sendingUser) throws RemoteException {
22980                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
22981                            reportStatus ? 1 : 0, 1, keys);
22982                    mHandler.sendMessage(msg);
22983                }
22984            });
22985        } else {
22986            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
22987                    keys);
22988            mHandler.sendMessage(msg);
22989        }
22990    }
22991
22992    private void loadPrivatePackages(final VolumeInfo vol) {
22993        mHandler.post(new Runnable() {
22994            @Override
22995            public void run() {
22996                loadPrivatePackagesInner(vol);
22997            }
22998        });
22999    }
23000
23001    private void loadPrivatePackagesInner(VolumeInfo vol) {
23002        final String volumeUuid = vol.fsUuid;
23003        if (TextUtils.isEmpty(volumeUuid)) {
23004            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23005            return;
23006        }
23007
23008        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23009        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23010        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23011
23012        final VersionInfo ver;
23013        final List<PackageSetting> packages;
23014        synchronized (mPackages) {
23015            ver = mSettings.findOrCreateVersion(volumeUuid);
23016            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23017        }
23018
23019        for (PackageSetting ps : packages) {
23020            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23021            synchronized (mInstallLock) {
23022                final PackageParser.Package pkg;
23023                try {
23024                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23025                    loaded.add(pkg.applicationInfo);
23026
23027                } catch (PackageManagerException e) {
23028                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23029                }
23030
23031                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23032                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23033                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23034                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23035                }
23036            }
23037        }
23038
23039        // Reconcile app data for all started/unlocked users
23040        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23041        final UserManager um = mContext.getSystemService(UserManager.class);
23042        UserManagerInternal umInternal = getUserManagerInternal();
23043        for (UserInfo user : um.getUsers()) {
23044            final int flags;
23045            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23046                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23047            } else if (umInternal.isUserRunning(user.id)) {
23048                flags = StorageManager.FLAG_STORAGE_DE;
23049            } else {
23050                continue;
23051            }
23052
23053            try {
23054                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23055                synchronized (mInstallLock) {
23056                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23057                }
23058            } catch (IllegalStateException e) {
23059                // Device was probably ejected, and we'll process that event momentarily
23060                Slog.w(TAG, "Failed to prepare storage: " + e);
23061            }
23062        }
23063
23064        synchronized (mPackages) {
23065            int updateFlags = UPDATE_PERMISSIONS_ALL;
23066            if (ver.sdkVersion != mSdkVersion) {
23067                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23068                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23069                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23070            }
23071            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23072
23073            // Yay, everything is now upgraded
23074            ver.forceCurrent();
23075
23076            mSettings.writeLPr();
23077        }
23078
23079        for (PackageFreezer freezer : freezers) {
23080            freezer.close();
23081        }
23082
23083        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23084        sendResourcesChangedBroadcast(true, false, loaded, null);
23085        mLoadedVolumes.add(vol.getId());
23086    }
23087
23088    private void unloadPrivatePackages(final VolumeInfo vol) {
23089        mHandler.post(new Runnable() {
23090            @Override
23091            public void run() {
23092                unloadPrivatePackagesInner(vol);
23093            }
23094        });
23095    }
23096
23097    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23098        final String volumeUuid = vol.fsUuid;
23099        if (TextUtils.isEmpty(volumeUuid)) {
23100            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23101            return;
23102        }
23103
23104        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23105        synchronized (mInstallLock) {
23106        synchronized (mPackages) {
23107            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23108            for (PackageSetting ps : packages) {
23109                if (ps.pkg == null) continue;
23110
23111                final ApplicationInfo info = ps.pkg.applicationInfo;
23112                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23113                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23114
23115                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23116                        "unloadPrivatePackagesInner")) {
23117                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23118                            false, null)) {
23119                        unloaded.add(info);
23120                    } else {
23121                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23122                    }
23123                }
23124
23125                // Try very hard to release any references to this package
23126                // so we don't risk the system server being killed due to
23127                // open FDs
23128                AttributeCache.instance().removePackage(ps.name);
23129            }
23130
23131            mSettings.writeLPr();
23132        }
23133        }
23134
23135        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23136        sendResourcesChangedBroadcast(false, false, unloaded, null);
23137        mLoadedVolumes.remove(vol.getId());
23138
23139        // Try very hard to release any references to this path so we don't risk
23140        // the system server being killed due to open FDs
23141        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23142
23143        for (int i = 0; i < 3; i++) {
23144            System.gc();
23145            System.runFinalization();
23146        }
23147    }
23148
23149    private void assertPackageKnown(String volumeUuid, String packageName)
23150            throws PackageManagerException {
23151        synchronized (mPackages) {
23152            // Normalize package name to handle renamed packages
23153            packageName = normalizePackageNameLPr(packageName);
23154
23155            final PackageSetting ps = mSettings.mPackages.get(packageName);
23156            if (ps == null) {
23157                throw new PackageManagerException("Package " + packageName + " is unknown");
23158            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23159                throw new PackageManagerException(
23160                        "Package " + packageName + " found on unknown volume " + volumeUuid
23161                                + "; expected volume " + ps.volumeUuid);
23162            }
23163        }
23164    }
23165
23166    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23167            throws PackageManagerException {
23168        synchronized (mPackages) {
23169            // Normalize package name to handle renamed packages
23170            packageName = normalizePackageNameLPr(packageName);
23171
23172            final PackageSetting ps = mSettings.mPackages.get(packageName);
23173            if (ps == null) {
23174                throw new PackageManagerException("Package " + packageName + " is unknown");
23175            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23176                throw new PackageManagerException(
23177                        "Package " + packageName + " found on unknown volume " + volumeUuid
23178                                + "; expected volume " + ps.volumeUuid);
23179            } else if (!ps.getInstalled(userId)) {
23180                throw new PackageManagerException(
23181                        "Package " + packageName + " not installed for user " + userId);
23182            }
23183        }
23184    }
23185
23186    private List<String> collectAbsoluteCodePaths() {
23187        synchronized (mPackages) {
23188            List<String> codePaths = new ArrayList<>();
23189            final int packageCount = mSettings.mPackages.size();
23190            for (int i = 0; i < packageCount; i++) {
23191                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23192                codePaths.add(ps.codePath.getAbsolutePath());
23193            }
23194            return codePaths;
23195        }
23196    }
23197
23198    /**
23199     * Examine all apps present on given mounted volume, and destroy apps that
23200     * aren't expected, either due to uninstallation or reinstallation on
23201     * another volume.
23202     */
23203    private void reconcileApps(String volumeUuid) {
23204        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23205        List<File> filesToDelete = null;
23206
23207        final File[] files = FileUtils.listFilesOrEmpty(
23208                Environment.getDataAppDirectory(volumeUuid));
23209        for (File file : files) {
23210            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23211                    && !PackageInstallerService.isStageName(file.getName());
23212            if (!isPackage) {
23213                // Ignore entries which are not packages
23214                continue;
23215            }
23216
23217            String absolutePath = file.getAbsolutePath();
23218
23219            boolean pathValid = false;
23220            final int absoluteCodePathCount = absoluteCodePaths.size();
23221            for (int i = 0; i < absoluteCodePathCount; i++) {
23222                String absoluteCodePath = absoluteCodePaths.get(i);
23223                if (absolutePath.startsWith(absoluteCodePath)) {
23224                    pathValid = true;
23225                    break;
23226                }
23227            }
23228
23229            if (!pathValid) {
23230                if (filesToDelete == null) {
23231                    filesToDelete = new ArrayList<>();
23232                }
23233                filesToDelete.add(file);
23234            }
23235        }
23236
23237        if (filesToDelete != null) {
23238            final int fileToDeleteCount = filesToDelete.size();
23239            for (int i = 0; i < fileToDeleteCount; i++) {
23240                File fileToDelete = filesToDelete.get(i);
23241                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23242                synchronized (mInstallLock) {
23243                    removeCodePathLI(fileToDelete);
23244                }
23245            }
23246        }
23247    }
23248
23249    /**
23250     * Reconcile all app data for the given user.
23251     * <p>
23252     * Verifies that directories exist and that ownership and labeling is
23253     * correct for all installed apps on all mounted volumes.
23254     */
23255    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23256        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23257        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23258            final String volumeUuid = vol.getFsUuid();
23259            synchronized (mInstallLock) {
23260                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23261            }
23262        }
23263    }
23264
23265    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23266            boolean migrateAppData) {
23267        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23268    }
23269
23270    /**
23271     * Reconcile all app data on given mounted volume.
23272     * <p>
23273     * Destroys app data that isn't expected, either due to uninstallation or
23274     * reinstallation on another volume.
23275     * <p>
23276     * Verifies that directories exist and that ownership and labeling is
23277     * correct for all installed apps.
23278     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23279     */
23280    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23281            boolean migrateAppData, boolean onlyCoreApps) {
23282        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23283                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23284        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23285
23286        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23287        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23288
23289        // First look for stale data that doesn't belong, and check if things
23290        // have changed since we did our last restorecon
23291        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23292            if (StorageManager.isFileEncryptedNativeOrEmulated()
23293                    && !StorageManager.isUserKeyUnlocked(userId)) {
23294                throw new RuntimeException(
23295                        "Yikes, someone asked us to reconcile CE storage while " + userId
23296                                + " was still locked; this would have caused massive data loss!");
23297            }
23298
23299            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23300            for (File file : files) {
23301                final String packageName = file.getName();
23302                try {
23303                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23304                } catch (PackageManagerException e) {
23305                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23306                    try {
23307                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23308                                StorageManager.FLAG_STORAGE_CE, 0);
23309                    } catch (InstallerException e2) {
23310                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23311                    }
23312                }
23313            }
23314        }
23315        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23316            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23317            for (File file : files) {
23318                final String packageName = file.getName();
23319                try {
23320                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23321                } catch (PackageManagerException e) {
23322                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23323                    try {
23324                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23325                                StorageManager.FLAG_STORAGE_DE, 0);
23326                    } catch (InstallerException e2) {
23327                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23328                    }
23329                }
23330            }
23331        }
23332
23333        // Ensure that data directories are ready to roll for all packages
23334        // installed for this volume and user
23335        final List<PackageSetting> packages;
23336        synchronized (mPackages) {
23337            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23338        }
23339        int preparedCount = 0;
23340        for (PackageSetting ps : packages) {
23341            final String packageName = ps.name;
23342            if (ps.pkg == null) {
23343                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23344                // TODO: might be due to legacy ASEC apps; we should circle back
23345                // and reconcile again once they're scanned
23346                continue;
23347            }
23348            // Skip non-core apps if requested
23349            if (onlyCoreApps && !ps.pkg.coreApp) {
23350                result.add(packageName);
23351                continue;
23352            }
23353
23354            if (ps.getInstalled(userId)) {
23355                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23356                preparedCount++;
23357            }
23358        }
23359
23360        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23361        return result;
23362    }
23363
23364    /**
23365     * Prepare app data for the given app just after it was installed or
23366     * upgraded. This method carefully only touches users that it's installed
23367     * for, and it forces a restorecon to handle any seinfo changes.
23368     * <p>
23369     * Verifies that directories exist and that ownership and labeling is
23370     * correct for all installed apps. If there is an ownership mismatch, it
23371     * will try recovering system apps by wiping data; third-party app data is
23372     * left intact.
23373     * <p>
23374     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23375     */
23376    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23377        final PackageSetting ps;
23378        synchronized (mPackages) {
23379            ps = mSettings.mPackages.get(pkg.packageName);
23380            mSettings.writeKernelMappingLPr(ps);
23381        }
23382
23383        final UserManager um = mContext.getSystemService(UserManager.class);
23384        UserManagerInternal umInternal = getUserManagerInternal();
23385        for (UserInfo user : um.getUsers()) {
23386            final int flags;
23387            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23388                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23389            } else if (umInternal.isUserRunning(user.id)) {
23390                flags = StorageManager.FLAG_STORAGE_DE;
23391            } else {
23392                continue;
23393            }
23394
23395            if (ps.getInstalled(user.id)) {
23396                // TODO: when user data is locked, mark that we're still dirty
23397                prepareAppDataLIF(pkg, user.id, flags);
23398            }
23399        }
23400    }
23401
23402    /**
23403     * Prepare app data for the given app.
23404     * <p>
23405     * Verifies that directories exist and that ownership and labeling is
23406     * correct for all installed apps. If there is an ownership mismatch, this
23407     * will try recovering system apps by wiping data; third-party app data is
23408     * left intact.
23409     */
23410    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23411        if (pkg == null) {
23412            Slog.wtf(TAG, "Package was null!", new Throwable());
23413            return;
23414        }
23415        prepareAppDataLeafLIF(pkg, userId, flags);
23416        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23417        for (int i = 0; i < childCount; i++) {
23418            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23419        }
23420    }
23421
23422    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23423            boolean maybeMigrateAppData) {
23424        prepareAppDataLIF(pkg, userId, flags);
23425
23426        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23427            // We may have just shuffled around app data directories, so
23428            // prepare them one more time
23429            prepareAppDataLIF(pkg, userId, flags);
23430        }
23431    }
23432
23433    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23434        if (DEBUG_APP_DATA) {
23435            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23436                    + Integer.toHexString(flags));
23437        }
23438
23439        final String volumeUuid = pkg.volumeUuid;
23440        final String packageName = pkg.packageName;
23441        final ApplicationInfo app = pkg.applicationInfo;
23442        final int appId = UserHandle.getAppId(app.uid);
23443
23444        Preconditions.checkNotNull(app.seInfo);
23445
23446        long ceDataInode = -1;
23447        try {
23448            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23449                    appId, app.seInfo, app.targetSdkVersion);
23450        } catch (InstallerException e) {
23451            if (app.isSystemApp()) {
23452                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23453                        + ", but trying to recover: " + e);
23454                destroyAppDataLeafLIF(pkg, userId, flags);
23455                try {
23456                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23457                            appId, app.seInfo, app.targetSdkVersion);
23458                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23459                } catch (InstallerException e2) {
23460                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23461                }
23462            } else {
23463                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23464            }
23465        }
23466
23467        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23468            // TODO: mark this structure as dirty so we persist it!
23469            synchronized (mPackages) {
23470                final PackageSetting ps = mSettings.mPackages.get(packageName);
23471                if (ps != null) {
23472                    ps.setCeDataInode(ceDataInode, userId);
23473                }
23474            }
23475        }
23476
23477        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23478    }
23479
23480    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23481        if (pkg == null) {
23482            Slog.wtf(TAG, "Package was null!", new Throwable());
23483            return;
23484        }
23485        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23486        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23487        for (int i = 0; i < childCount; i++) {
23488            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23489        }
23490    }
23491
23492    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23493        final String volumeUuid = pkg.volumeUuid;
23494        final String packageName = pkg.packageName;
23495        final ApplicationInfo app = pkg.applicationInfo;
23496
23497        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23498            // Create a native library symlink only if we have native libraries
23499            // and if the native libraries are 32 bit libraries. We do not provide
23500            // this symlink for 64 bit libraries.
23501            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23502                final String nativeLibPath = app.nativeLibraryDir;
23503                try {
23504                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23505                            nativeLibPath, userId);
23506                } catch (InstallerException e) {
23507                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23508                }
23509            }
23510        }
23511    }
23512
23513    /**
23514     * For system apps on non-FBE devices, this method migrates any existing
23515     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23516     * requested by the app.
23517     */
23518    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23519        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23520                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23521            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23522                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23523            try {
23524                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23525                        storageTarget);
23526            } catch (InstallerException e) {
23527                logCriticalInfo(Log.WARN,
23528                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23529            }
23530            return true;
23531        } else {
23532            return false;
23533        }
23534    }
23535
23536    public PackageFreezer freezePackage(String packageName, String killReason) {
23537        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23538    }
23539
23540    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23541        return new PackageFreezer(packageName, userId, killReason);
23542    }
23543
23544    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23545            String killReason) {
23546        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23547    }
23548
23549    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23550            String killReason) {
23551        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23552            return new PackageFreezer();
23553        } else {
23554            return freezePackage(packageName, userId, killReason);
23555        }
23556    }
23557
23558    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23559            String killReason) {
23560        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23561    }
23562
23563    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23564            String killReason) {
23565        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23566            return new PackageFreezer();
23567        } else {
23568            return freezePackage(packageName, userId, killReason);
23569        }
23570    }
23571
23572    /**
23573     * Class that freezes and kills the given package upon creation, and
23574     * unfreezes it upon closing. This is typically used when doing surgery on
23575     * app code/data to prevent the app from running while you're working.
23576     */
23577    private class PackageFreezer implements AutoCloseable {
23578        private final String mPackageName;
23579        private final PackageFreezer[] mChildren;
23580
23581        private final boolean mWeFroze;
23582
23583        private final AtomicBoolean mClosed = new AtomicBoolean();
23584        private final CloseGuard mCloseGuard = CloseGuard.get();
23585
23586        /**
23587         * Create and return a stub freezer that doesn't actually do anything,
23588         * typically used when someone requested
23589         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23590         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23591         */
23592        public PackageFreezer() {
23593            mPackageName = null;
23594            mChildren = null;
23595            mWeFroze = false;
23596            mCloseGuard.open("close");
23597        }
23598
23599        public PackageFreezer(String packageName, int userId, String killReason) {
23600            synchronized (mPackages) {
23601                mPackageName = packageName;
23602                mWeFroze = mFrozenPackages.add(mPackageName);
23603
23604                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23605                if (ps != null) {
23606                    killApplication(ps.name, ps.appId, userId, killReason);
23607                }
23608
23609                final PackageParser.Package p = mPackages.get(packageName);
23610                if (p != null && p.childPackages != null) {
23611                    final int N = p.childPackages.size();
23612                    mChildren = new PackageFreezer[N];
23613                    for (int i = 0; i < N; i++) {
23614                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23615                                userId, killReason);
23616                    }
23617                } else {
23618                    mChildren = null;
23619                }
23620            }
23621            mCloseGuard.open("close");
23622        }
23623
23624        @Override
23625        protected void finalize() throws Throwable {
23626            try {
23627                if (mCloseGuard != null) {
23628                    mCloseGuard.warnIfOpen();
23629                }
23630
23631                close();
23632            } finally {
23633                super.finalize();
23634            }
23635        }
23636
23637        @Override
23638        public void close() {
23639            mCloseGuard.close();
23640            if (mClosed.compareAndSet(false, true)) {
23641                synchronized (mPackages) {
23642                    if (mWeFroze) {
23643                        mFrozenPackages.remove(mPackageName);
23644                    }
23645
23646                    if (mChildren != null) {
23647                        for (PackageFreezer freezer : mChildren) {
23648                            freezer.close();
23649                        }
23650                    }
23651                }
23652            }
23653        }
23654    }
23655
23656    /**
23657     * Verify that given package is currently frozen.
23658     */
23659    private void checkPackageFrozen(String packageName) {
23660        synchronized (mPackages) {
23661            if (!mFrozenPackages.contains(packageName)) {
23662                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23663            }
23664        }
23665    }
23666
23667    @Override
23668    public int movePackage(final String packageName, final String volumeUuid) {
23669        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23670
23671        final int callingUid = Binder.getCallingUid();
23672        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
23673        final int moveId = mNextMoveId.getAndIncrement();
23674        mHandler.post(new Runnable() {
23675            @Override
23676            public void run() {
23677                try {
23678                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
23679                } catch (PackageManagerException e) {
23680                    Slog.w(TAG, "Failed to move " + packageName, e);
23681                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
23682                }
23683            }
23684        });
23685        return moveId;
23686    }
23687
23688    private void movePackageInternal(final String packageName, final String volumeUuid,
23689            final int moveId, final int callingUid, UserHandle user)
23690                    throws PackageManagerException {
23691        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23692        final PackageManager pm = mContext.getPackageManager();
23693
23694        final boolean currentAsec;
23695        final String currentVolumeUuid;
23696        final File codeFile;
23697        final String installerPackageName;
23698        final String packageAbiOverride;
23699        final int appId;
23700        final String seinfo;
23701        final String label;
23702        final int targetSdkVersion;
23703        final PackageFreezer freezer;
23704        final int[] installedUserIds;
23705
23706        // reader
23707        synchronized (mPackages) {
23708            final PackageParser.Package pkg = mPackages.get(packageName);
23709            final PackageSetting ps = mSettings.mPackages.get(packageName);
23710            if (pkg == null
23711                    || ps == null
23712                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
23713                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
23714            }
23715            if (pkg.applicationInfo.isSystemApp()) {
23716                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
23717                        "Cannot move system application");
23718            }
23719
23720            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
23721            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
23722                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
23723            if (isInternalStorage && !allow3rdPartyOnInternal) {
23724                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
23725                        "3rd party apps are not allowed on internal storage");
23726            }
23727
23728            if (pkg.applicationInfo.isExternalAsec()) {
23729                currentAsec = true;
23730                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
23731            } else if (pkg.applicationInfo.isForwardLocked()) {
23732                currentAsec = true;
23733                currentVolumeUuid = "forward_locked";
23734            } else {
23735                currentAsec = false;
23736                currentVolumeUuid = ps.volumeUuid;
23737
23738                final File probe = new File(pkg.codePath);
23739                final File probeOat = new File(probe, "oat");
23740                if (!probe.isDirectory() || !probeOat.isDirectory()) {
23741                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23742                            "Move only supported for modern cluster style installs");
23743                }
23744            }
23745
23746            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
23747                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23748                        "Package already moved to " + volumeUuid);
23749            }
23750            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
23751                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
23752                        "Device admin cannot be moved");
23753            }
23754
23755            if (mFrozenPackages.contains(packageName)) {
23756                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
23757                        "Failed to move already frozen package");
23758            }
23759
23760            codeFile = new File(pkg.codePath);
23761            installerPackageName = ps.installerPackageName;
23762            packageAbiOverride = ps.cpuAbiOverrideString;
23763            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
23764            seinfo = pkg.applicationInfo.seInfo;
23765            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
23766            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
23767            freezer = freezePackage(packageName, "movePackageInternal");
23768            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
23769        }
23770
23771        final Bundle extras = new Bundle();
23772        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
23773        extras.putString(Intent.EXTRA_TITLE, label);
23774        mMoveCallbacks.notifyCreated(moveId, extras);
23775
23776        int installFlags;
23777        final boolean moveCompleteApp;
23778        final File measurePath;
23779
23780        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
23781            installFlags = INSTALL_INTERNAL;
23782            moveCompleteApp = !currentAsec;
23783            measurePath = Environment.getDataAppDirectory(volumeUuid);
23784        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
23785            installFlags = INSTALL_EXTERNAL;
23786            moveCompleteApp = false;
23787            measurePath = storage.getPrimaryPhysicalVolume().getPath();
23788        } else {
23789            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
23790            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
23791                    || !volume.isMountedWritable()) {
23792                freezer.close();
23793                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23794                        "Move location not mounted private volume");
23795            }
23796
23797            Preconditions.checkState(!currentAsec);
23798
23799            installFlags = INSTALL_INTERNAL;
23800            moveCompleteApp = true;
23801            measurePath = Environment.getDataAppDirectory(volumeUuid);
23802        }
23803
23804        // If we're moving app data around, we need all the users unlocked
23805        if (moveCompleteApp) {
23806            for (int userId : installedUserIds) {
23807                if (StorageManager.isFileEncryptedNativeOrEmulated()
23808                        && !StorageManager.isUserKeyUnlocked(userId)) {
23809                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
23810                            "User " + userId + " must be unlocked");
23811                }
23812            }
23813        }
23814
23815        final PackageStats stats = new PackageStats(null, -1);
23816        synchronized (mInstaller) {
23817            for (int userId : installedUserIds) {
23818                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
23819                    freezer.close();
23820                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23821                            "Failed to measure package size");
23822                }
23823            }
23824        }
23825
23826        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
23827                + stats.dataSize);
23828
23829        final long startFreeBytes = measurePath.getUsableSpace();
23830        final long sizeBytes;
23831        if (moveCompleteApp) {
23832            sizeBytes = stats.codeSize + stats.dataSize;
23833        } else {
23834            sizeBytes = stats.codeSize;
23835        }
23836
23837        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23838            freezer.close();
23839            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23840                    "Not enough free space to move");
23841        }
23842
23843        mMoveCallbacks.notifyStatusChanged(moveId, 10);
23844
23845        final CountDownLatch installedLatch = new CountDownLatch(1);
23846        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23847            @Override
23848            public void onUserActionRequired(Intent intent) throws RemoteException {
23849                throw new IllegalStateException();
23850            }
23851
23852            @Override
23853            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23854                    Bundle extras) throws RemoteException {
23855                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23856                        + PackageManager.installStatusToString(returnCode, msg));
23857
23858                installedLatch.countDown();
23859                freezer.close();
23860
23861                final int status = PackageManager.installStatusToPublicStatus(returnCode);
23862                switch (status) {
23863                    case PackageInstaller.STATUS_SUCCESS:
23864                        mMoveCallbacks.notifyStatusChanged(moveId,
23865                                PackageManager.MOVE_SUCCEEDED);
23866                        break;
23867                    case PackageInstaller.STATUS_FAILURE_STORAGE:
23868                        mMoveCallbacks.notifyStatusChanged(moveId,
23869                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23870                        break;
23871                    default:
23872                        mMoveCallbacks.notifyStatusChanged(moveId,
23873                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23874                        break;
23875                }
23876            }
23877        };
23878
23879        final MoveInfo move;
23880        if (moveCompleteApp) {
23881            // Kick off a thread to report progress estimates
23882            new Thread() {
23883                @Override
23884                public void run() {
23885                    while (true) {
23886                        try {
23887                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
23888                                break;
23889                            }
23890                        } catch (InterruptedException ignored) {
23891                        }
23892
23893                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23894                        final int progress = 10 + (int) MathUtils.constrain(
23895                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23896                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
23897                    }
23898                }
23899            }.start();
23900
23901            final String dataAppName = codeFile.getName();
23902            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23903                    dataAppName, appId, seinfo, targetSdkVersion);
23904        } else {
23905            move = null;
23906        }
23907
23908        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23909
23910        final Message msg = mHandler.obtainMessage(INIT_COPY);
23911        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23912        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23913                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23914                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
23915                PackageManager.INSTALL_REASON_UNKNOWN);
23916        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23917        msg.obj = params;
23918
23919        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23920                System.identityHashCode(msg.obj));
23921        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23922                System.identityHashCode(msg.obj));
23923
23924        mHandler.sendMessage(msg);
23925    }
23926
23927    @Override
23928    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23929        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23930
23931        final int realMoveId = mNextMoveId.getAndIncrement();
23932        final Bundle extras = new Bundle();
23933        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23934        mMoveCallbacks.notifyCreated(realMoveId, extras);
23935
23936        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23937            @Override
23938            public void onCreated(int moveId, Bundle extras) {
23939                // Ignored
23940            }
23941
23942            @Override
23943            public void onStatusChanged(int moveId, int status, long estMillis) {
23944                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23945            }
23946        };
23947
23948        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23949        storage.setPrimaryStorageUuid(volumeUuid, callback);
23950        return realMoveId;
23951    }
23952
23953    @Override
23954    public int getMoveStatus(int moveId) {
23955        mContext.enforceCallingOrSelfPermission(
23956                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23957        return mMoveCallbacks.mLastStatus.get(moveId);
23958    }
23959
23960    @Override
23961    public void registerMoveCallback(IPackageMoveObserver callback) {
23962        mContext.enforceCallingOrSelfPermission(
23963                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23964        mMoveCallbacks.register(callback);
23965    }
23966
23967    @Override
23968    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23969        mContext.enforceCallingOrSelfPermission(
23970                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23971        mMoveCallbacks.unregister(callback);
23972    }
23973
23974    @Override
23975    public boolean setInstallLocation(int loc) {
23976        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23977                null);
23978        if (getInstallLocation() == loc) {
23979            return true;
23980        }
23981        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23982                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23983            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23984                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23985            return true;
23986        }
23987        return false;
23988   }
23989
23990    @Override
23991    public int getInstallLocation() {
23992        // allow instant app access
23993        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23994                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23995                PackageHelper.APP_INSTALL_AUTO);
23996    }
23997
23998    /** Called by UserManagerService */
23999    void cleanUpUser(UserManagerService userManager, int userHandle) {
24000        synchronized (mPackages) {
24001            mDirtyUsers.remove(userHandle);
24002            mUserNeedsBadging.delete(userHandle);
24003            mSettings.removeUserLPw(userHandle);
24004            mPendingBroadcasts.remove(userHandle);
24005            mInstantAppRegistry.onUserRemovedLPw(userHandle);
24006            removeUnusedPackagesLPw(userManager, userHandle);
24007        }
24008    }
24009
24010    /**
24011     * We're removing userHandle and would like to remove any downloaded packages
24012     * that are no longer in use by any other user.
24013     * @param userHandle the user being removed
24014     */
24015    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24016        final boolean DEBUG_CLEAN_APKS = false;
24017        int [] users = userManager.getUserIds();
24018        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24019        while (psit.hasNext()) {
24020            PackageSetting ps = psit.next();
24021            if (ps.pkg == null) {
24022                continue;
24023            }
24024            final String packageName = ps.pkg.packageName;
24025            // Skip over if system app
24026            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24027                continue;
24028            }
24029            if (DEBUG_CLEAN_APKS) {
24030                Slog.i(TAG, "Checking package " + packageName);
24031            }
24032            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24033            if (keep) {
24034                if (DEBUG_CLEAN_APKS) {
24035                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24036                }
24037            } else {
24038                for (int i = 0; i < users.length; i++) {
24039                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24040                        keep = true;
24041                        if (DEBUG_CLEAN_APKS) {
24042                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24043                                    + users[i]);
24044                        }
24045                        break;
24046                    }
24047                }
24048            }
24049            if (!keep) {
24050                if (DEBUG_CLEAN_APKS) {
24051                    Slog.i(TAG, "  Removing package " + packageName);
24052                }
24053                mHandler.post(new Runnable() {
24054                    public void run() {
24055                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24056                                userHandle, 0);
24057                    } //end run
24058                });
24059            }
24060        }
24061    }
24062
24063    /** Called by UserManagerService */
24064    void createNewUser(int userId, String[] disallowedPackages) {
24065        synchronized (mInstallLock) {
24066            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24067        }
24068        synchronized (mPackages) {
24069            scheduleWritePackageRestrictionsLocked(userId);
24070            scheduleWritePackageListLocked(userId);
24071            applyFactoryDefaultBrowserLPw(userId);
24072            primeDomainVerificationsLPw(userId);
24073        }
24074    }
24075
24076    void onNewUserCreated(final int userId) {
24077        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24078        // If permission review for legacy apps is required, we represent
24079        // dagerous permissions for such apps as always granted runtime
24080        // permissions to keep per user flag state whether review is needed.
24081        // Hence, if a new user is added we have to propagate dangerous
24082        // permission grants for these legacy apps.
24083        if (mPermissionReviewRequired) {
24084            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24085                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24086        }
24087    }
24088
24089    @Override
24090    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24091        mContext.enforceCallingOrSelfPermission(
24092                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24093                "Only package verification agents can read the verifier device identity");
24094
24095        synchronized (mPackages) {
24096            return mSettings.getVerifierDeviceIdentityLPw();
24097        }
24098    }
24099
24100    @Override
24101    public void setPermissionEnforced(String permission, boolean enforced) {
24102        // TODO: Now that we no longer change GID for storage, this should to away.
24103        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24104                "setPermissionEnforced");
24105        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24106            synchronized (mPackages) {
24107                if (mSettings.mReadExternalStorageEnforced == null
24108                        || mSettings.mReadExternalStorageEnforced != enforced) {
24109                    mSettings.mReadExternalStorageEnforced = enforced;
24110                    mSettings.writeLPr();
24111                }
24112            }
24113            // kill any non-foreground processes so we restart them and
24114            // grant/revoke the GID.
24115            final IActivityManager am = ActivityManager.getService();
24116            if (am != null) {
24117                final long token = Binder.clearCallingIdentity();
24118                try {
24119                    am.killProcessesBelowForeground("setPermissionEnforcement");
24120                } catch (RemoteException e) {
24121                } finally {
24122                    Binder.restoreCallingIdentity(token);
24123                }
24124            }
24125        } else {
24126            throw new IllegalArgumentException("No selective enforcement for " + permission);
24127        }
24128    }
24129
24130    @Override
24131    @Deprecated
24132    public boolean isPermissionEnforced(String permission) {
24133        // allow instant applications
24134        return true;
24135    }
24136
24137    @Override
24138    public boolean isStorageLow() {
24139        // allow instant applications
24140        final long token = Binder.clearCallingIdentity();
24141        try {
24142            final DeviceStorageMonitorInternal
24143                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24144            if (dsm != null) {
24145                return dsm.isMemoryLow();
24146            } else {
24147                return false;
24148            }
24149        } finally {
24150            Binder.restoreCallingIdentity(token);
24151        }
24152    }
24153
24154    @Override
24155    public IPackageInstaller getPackageInstaller() {
24156        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24157            return null;
24158        }
24159        return mInstallerService;
24160    }
24161
24162    private boolean userNeedsBadging(int userId) {
24163        int index = mUserNeedsBadging.indexOfKey(userId);
24164        if (index < 0) {
24165            final UserInfo userInfo;
24166            final long token = Binder.clearCallingIdentity();
24167            try {
24168                userInfo = sUserManager.getUserInfo(userId);
24169            } finally {
24170                Binder.restoreCallingIdentity(token);
24171            }
24172            final boolean b;
24173            if (userInfo != null && userInfo.isManagedProfile()) {
24174                b = true;
24175            } else {
24176                b = false;
24177            }
24178            mUserNeedsBadging.put(userId, b);
24179            return b;
24180        }
24181        return mUserNeedsBadging.valueAt(index);
24182    }
24183
24184    @Override
24185    public KeySet getKeySetByAlias(String packageName, String alias) {
24186        if (packageName == null || alias == null) {
24187            return null;
24188        }
24189        synchronized(mPackages) {
24190            final PackageParser.Package pkg = mPackages.get(packageName);
24191            if (pkg == null) {
24192                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24193                throw new IllegalArgumentException("Unknown package: " + packageName);
24194            }
24195            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24196            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24197                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24198                throw new IllegalArgumentException("Unknown package: " + packageName);
24199            }
24200            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24201            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24202        }
24203    }
24204
24205    @Override
24206    public KeySet getSigningKeySet(String packageName) {
24207        if (packageName == null) {
24208            return null;
24209        }
24210        synchronized(mPackages) {
24211            final int callingUid = Binder.getCallingUid();
24212            final int callingUserId = UserHandle.getUserId(callingUid);
24213            final PackageParser.Package pkg = mPackages.get(packageName);
24214            if (pkg == null) {
24215                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24216                throw new IllegalArgumentException("Unknown package: " + packageName);
24217            }
24218            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24219            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24220                // filter and pretend the package doesn't exist
24221                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24222                        + ", uid:" + callingUid);
24223                throw new IllegalArgumentException("Unknown package: " + packageName);
24224            }
24225            if (pkg.applicationInfo.uid != callingUid
24226                    && Process.SYSTEM_UID != callingUid) {
24227                throw new SecurityException("May not access signing KeySet of other apps.");
24228            }
24229            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24230            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24231        }
24232    }
24233
24234    @Override
24235    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24236        final int callingUid = Binder.getCallingUid();
24237        if (getInstantAppPackageName(callingUid) != null) {
24238            return false;
24239        }
24240        if (packageName == null || ks == null) {
24241            return false;
24242        }
24243        synchronized(mPackages) {
24244            final PackageParser.Package pkg = mPackages.get(packageName);
24245            if (pkg == null
24246                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24247                            UserHandle.getUserId(callingUid))) {
24248                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24249                throw new IllegalArgumentException("Unknown package: " + packageName);
24250            }
24251            IBinder ksh = ks.getToken();
24252            if (ksh instanceof KeySetHandle) {
24253                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24254                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24255            }
24256            return false;
24257        }
24258    }
24259
24260    @Override
24261    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24262        final int callingUid = Binder.getCallingUid();
24263        if (getInstantAppPackageName(callingUid) != null) {
24264            return false;
24265        }
24266        if (packageName == null || ks == null) {
24267            return false;
24268        }
24269        synchronized(mPackages) {
24270            final PackageParser.Package pkg = mPackages.get(packageName);
24271            if (pkg == null
24272                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24273                            UserHandle.getUserId(callingUid))) {
24274                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24275                throw new IllegalArgumentException("Unknown package: " + packageName);
24276            }
24277            IBinder ksh = ks.getToken();
24278            if (ksh instanceof KeySetHandle) {
24279                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24280                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24281            }
24282            return false;
24283        }
24284    }
24285
24286    private void deletePackageIfUnusedLPr(final String packageName) {
24287        PackageSetting ps = mSettings.mPackages.get(packageName);
24288        if (ps == null) {
24289            return;
24290        }
24291        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24292            // TODO Implement atomic delete if package is unused
24293            // It is currently possible that the package will be deleted even if it is installed
24294            // after this method returns.
24295            mHandler.post(new Runnable() {
24296                public void run() {
24297                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24298                            0, PackageManager.DELETE_ALL_USERS);
24299                }
24300            });
24301        }
24302    }
24303
24304    /**
24305     * Check and throw if the given before/after packages would be considered a
24306     * downgrade.
24307     */
24308    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24309            throws PackageManagerException {
24310        if (after.versionCode < before.mVersionCode) {
24311            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24312                    "Update version code " + after.versionCode + " is older than current "
24313                    + before.mVersionCode);
24314        } else if (after.versionCode == before.mVersionCode) {
24315            if (after.baseRevisionCode < before.baseRevisionCode) {
24316                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24317                        "Update base revision code " + after.baseRevisionCode
24318                        + " is older than current " + before.baseRevisionCode);
24319            }
24320
24321            if (!ArrayUtils.isEmpty(after.splitNames)) {
24322                for (int i = 0; i < after.splitNames.length; i++) {
24323                    final String splitName = after.splitNames[i];
24324                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24325                    if (j != -1) {
24326                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24327                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24328                                    "Update split " + splitName + " revision code "
24329                                    + after.splitRevisionCodes[i] + " is older than current "
24330                                    + before.splitRevisionCodes[j]);
24331                        }
24332                    }
24333                }
24334            }
24335        }
24336    }
24337
24338    private static class MoveCallbacks extends Handler {
24339        private static final int MSG_CREATED = 1;
24340        private static final int MSG_STATUS_CHANGED = 2;
24341
24342        private final RemoteCallbackList<IPackageMoveObserver>
24343                mCallbacks = new RemoteCallbackList<>();
24344
24345        private final SparseIntArray mLastStatus = new SparseIntArray();
24346
24347        public MoveCallbacks(Looper looper) {
24348            super(looper);
24349        }
24350
24351        public void register(IPackageMoveObserver callback) {
24352            mCallbacks.register(callback);
24353        }
24354
24355        public void unregister(IPackageMoveObserver callback) {
24356            mCallbacks.unregister(callback);
24357        }
24358
24359        @Override
24360        public void handleMessage(Message msg) {
24361            final SomeArgs args = (SomeArgs) msg.obj;
24362            final int n = mCallbacks.beginBroadcast();
24363            for (int i = 0; i < n; i++) {
24364                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24365                try {
24366                    invokeCallback(callback, msg.what, args);
24367                } catch (RemoteException ignored) {
24368                }
24369            }
24370            mCallbacks.finishBroadcast();
24371            args.recycle();
24372        }
24373
24374        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24375                throws RemoteException {
24376            switch (what) {
24377                case MSG_CREATED: {
24378                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24379                    break;
24380                }
24381                case MSG_STATUS_CHANGED: {
24382                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24383                    break;
24384                }
24385            }
24386        }
24387
24388        private void notifyCreated(int moveId, Bundle extras) {
24389            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24390
24391            final SomeArgs args = SomeArgs.obtain();
24392            args.argi1 = moveId;
24393            args.arg2 = extras;
24394            obtainMessage(MSG_CREATED, args).sendToTarget();
24395        }
24396
24397        private void notifyStatusChanged(int moveId, int status) {
24398            notifyStatusChanged(moveId, status, -1);
24399        }
24400
24401        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24402            Slog.v(TAG, "Move " + moveId + " status " + status);
24403
24404            final SomeArgs args = SomeArgs.obtain();
24405            args.argi1 = moveId;
24406            args.argi2 = status;
24407            args.arg3 = estMillis;
24408            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24409
24410            synchronized (mLastStatus) {
24411                mLastStatus.put(moveId, status);
24412            }
24413        }
24414    }
24415
24416    private final static class OnPermissionChangeListeners extends Handler {
24417        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24418
24419        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24420                new RemoteCallbackList<>();
24421
24422        public OnPermissionChangeListeners(Looper looper) {
24423            super(looper);
24424        }
24425
24426        @Override
24427        public void handleMessage(Message msg) {
24428            switch (msg.what) {
24429                case MSG_ON_PERMISSIONS_CHANGED: {
24430                    final int uid = msg.arg1;
24431                    handleOnPermissionsChanged(uid);
24432                } break;
24433            }
24434        }
24435
24436        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24437            mPermissionListeners.register(listener);
24438
24439        }
24440
24441        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24442            mPermissionListeners.unregister(listener);
24443        }
24444
24445        public void onPermissionsChanged(int uid) {
24446            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24447                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24448            }
24449        }
24450
24451        private void handleOnPermissionsChanged(int uid) {
24452            final int count = mPermissionListeners.beginBroadcast();
24453            try {
24454                for (int i = 0; i < count; i++) {
24455                    IOnPermissionsChangeListener callback = mPermissionListeners
24456                            .getBroadcastItem(i);
24457                    try {
24458                        callback.onPermissionsChanged(uid);
24459                    } catch (RemoteException e) {
24460                        Log.e(TAG, "Permission listener is dead", e);
24461                    }
24462                }
24463            } finally {
24464                mPermissionListeners.finishBroadcast();
24465            }
24466        }
24467    }
24468
24469    private class PackageManagerInternalImpl extends PackageManagerInternal {
24470        @Override
24471        public void setLocationPackagesProvider(PackagesProvider provider) {
24472            synchronized (mPackages) {
24473                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24474            }
24475        }
24476
24477        @Override
24478        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24479            synchronized (mPackages) {
24480                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24481            }
24482        }
24483
24484        @Override
24485        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24486            synchronized (mPackages) {
24487                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24488            }
24489        }
24490
24491        @Override
24492        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24493            synchronized (mPackages) {
24494                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24495            }
24496        }
24497
24498        @Override
24499        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24500            synchronized (mPackages) {
24501                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24502            }
24503        }
24504
24505        @Override
24506        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24507            synchronized (mPackages) {
24508                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24509            }
24510        }
24511
24512        @Override
24513        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24514            synchronized (mPackages) {
24515                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24516                        packageName, userId);
24517            }
24518        }
24519
24520        @Override
24521        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24522            synchronized (mPackages) {
24523                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24524                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24525                        packageName, userId);
24526            }
24527        }
24528
24529        @Override
24530        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24531            synchronized (mPackages) {
24532                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24533                        packageName, userId);
24534            }
24535        }
24536
24537        @Override
24538        public void setKeepUninstalledPackages(final List<String> packageList) {
24539            Preconditions.checkNotNull(packageList);
24540            List<String> removedFromList = null;
24541            synchronized (mPackages) {
24542                if (mKeepUninstalledPackages != null) {
24543                    final int packagesCount = mKeepUninstalledPackages.size();
24544                    for (int i = 0; i < packagesCount; i++) {
24545                        String oldPackage = mKeepUninstalledPackages.get(i);
24546                        if (packageList != null && packageList.contains(oldPackage)) {
24547                            continue;
24548                        }
24549                        if (removedFromList == null) {
24550                            removedFromList = new ArrayList<>();
24551                        }
24552                        removedFromList.add(oldPackage);
24553                    }
24554                }
24555                mKeepUninstalledPackages = new ArrayList<>(packageList);
24556                if (removedFromList != null) {
24557                    final int removedCount = removedFromList.size();
24558                    for (int i = 0; i < removedCount; i++) {
24559                        deletePackageIfUnusedLPr(removedFromList.get(i));
24560                    }
24561                }
24562            }
24563        }
24564
24565        @Override
24566        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24567            synchronized (mPackages) {
24568                // If we do not support permission review, done.
24569                if (!mPermissionReviewRequired) {
24570                    return false;
24571                }
24572
24573                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24574                if (packageSetting == null) {
24575                    return false;
24576                }
24577
24578                // Permission review applies only to apps not supporting the new permission model.
24579                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24580                    return false;
24581                }
24582
24583                // Legacy apps have the permission and get user consent on launch.
24584                PermissionsState permissionsState = packageSetting.getPermissionsState();
24585                return permissionsState.isPermissionReviewRequired(userId);
24586            }
24587        }
24588
24589        @Override
24590        public PackageInfo getPackageInfo(
24591                String packageName, int flags, int filterCallingUid, int userId) {
24592            return PackageManagerService.this
24593                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
24594                            flags, filterCallingUid, userId);
24595        }
24596
24597        @Override
24598        public ApplicationInfo getApplicationInfo(
24599                String packageName, int flags, int filterCallingUid, int userId) {
24600            return PackageManagerService.this
24601                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24602        }
24603
24604        @Override
24605        public ActivityInfo getActivityInfo(
24606                ComponentName component, int flags, int filterCallingUid, int userId) {
24607            return PackageManagerService.this
24608                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24609        }
24610
24611        @Override
24612        public List<ResolveInfo> queryIntentActivities(
24613                Intent intent, int flags, int filterCallingUid, int userId) {
24614            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24615            return PackageManagerService.this
24616                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24617                            userId, false /*resolveForStart*/);
24618        }
24619
24620        @Override
24621        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24622                int userId) {
24623            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24624        }
24625
24626        @Override
24627        public void setDeviceAndProfileOwnerPackages(
24628                int deviceOwnerUserId, String deviceOwnerPackage,
24629                SparseArray<String> profileOwnerPackages) {
24630            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24631                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24632        }
24633
24634        @Override
24635        public boolean isPackageDataProtected(int userId, String packageName) {
24636            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24637        }
24638
24639        @Override
24640        public boolean isPackageEphemeral(int userId, String packageName) {
24641            synchronized (mPackages) {
24642                final PackageSetting ps = mSettings.mPackages.get(packageName);
24643                return ps != null ? ps.getInstantApp(userId) : false;
24644            }
24645        }
24646
24647        @Override
24648        public boolean wasPackageEverLaunched(String packageName, int userId) {
24649            synchronized (mPackages) {
24650                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24651            }
24652        }
24653
24654        @Override
24655        public void grantRuntimePermission(String packageName, String name, int userId,
24656                boolean overridePolicy) {
24657            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24658                    overridePolicy);
24659        }
24660
24661        @Override
24662        public void revokeRuntimePermission(String packageName, String name, int userId,
24663                boolean overridePolicy) {
24664            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
24665                    overridePolicy);
24666        }
24667
24668        @Override
24669        public String getNameForUid(int uid) {
24670            return PackageManagerService.this.getNameForUid(uid);
24671        }
24672
24673        @Override
24674        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24675                Intent origIntent, String resolvedType, String callingPackage,
24676                Bundle verificationBundle, int userId) {
24677            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24678                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24679                    userId);
24680        }
24681
24682        @Override
24683        public void grantEphemeralAccess(int userId, Intent intent,
24684                int targetAppId, int ephemeralAppId) {
24685            synchronized (mPackages) {
24686                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24687                        targetAppId, ephemeralAppId);
24688            }
24689        }
24690
24691        @Override
24692        public boolean isInstantAppInstallerComponent(ComponentName component) {
24693            synchronized (mPackages) {
24694                return mInstantAppInstallerActivity != null
24695                        && mInstantAppInstallerActivity.getComponentName().equals(component);
24696            }
24697        }
24698
24699        @Override
24700        public void pruneInstantApps() {
24701            mInstantAppRegistry.pruneInstantApps();
24702        }
24703
24704        @Override
24705        public String getSetupWizardPackageName() {
24706            return mSetupWizardPackage;
24707        }
24708
24709        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24710            if (policy != null) {
24711                mExternalSourcesPolicy = policy;
24712            }
24713        }
24714
24715        @Override
24716        public boolean isPackagePersistent(String packageName) {
24717            synchronized (mPackages) {
24718                PackageParser.Package pkg = mPackages.get(packageName);
24719                return pkg != null
24720                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24721                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24722                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24723                        : false;
24724            }
24725        }
24726
24727        @Override
24728        public List<PackageInfo> getOverlayPackages(int userId) {
24729            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24730            synchronized (mPackages) {
24731                for (PackageParser.Package p : mPackages.values()) {
24732                    if (p.mOverlayTarget != null) {
24733                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24734                        if (pkg != null) {
24735                            overlayPackages.add(pkg);
24736                        }
24737                    }
24738                }
24739            }
24740            return overlayPackages;
24741        }
24742
24743        @Override
24744        public List<String> getTargetPackageNames(int userId) {
24745            List<String> targetPackages = new ArrayList<>();
24746            synchronized (mPackages) {
24747                for (PackageParser.Package p : mPackages.values()) {
24748                    if (p.mOverlayTarget == null) {
24749                        targetPackages.add(p.packageName);
24750                    }
24751                }
24752            }
24753            return targetPackages;
24754        }
24755
24756        @Override
24757        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24758                @Nullable List<String> overlayPackageNames) {
24759            synchronized (mPackages) {
24760                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24761                    Slog.e(TAG, "failed to find package " + targetPackageName);
24762                    return false;
24763                }
24764                ArrayList<String> overlayPaths = null;
24765                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24766                    final int N = overlayPackageNames.size();
24767                    overlayPaths = new ArrayList<>(N);
24768                    for (int i = 0; i < N; i++) {
24769                        final String packageName = overlayPackageNames.get(i);
24770                        final PackageParser.Package pkg = mPackages.get(packageName);
24771                        if (pkg == null) {
24772                            Slog.e(TAG, "failed to find package " + packageName);
24773                            return false;
24774                        }
24775                        overlayPaths.add(pkg.baseCodePath);
24776                    }
24777                }
24778
24779                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24780                ps.setOverlayPaths(overlayPaths, userId);
24781                return true;
24782            }
24783        }
24784
24785        @Override
24786        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24787                int flags, int userId) {
24788            return resolveIntentInternal(
24789                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
24790        }
24791
24792        @Override
24793        public ResolveInfo resolveService(Intent intent, String resolvedType,
24794                int flags, int userId, int callingUid) {
24795            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24796        }
24797
24798        @Override
24799        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24800            synchronized (mPackages) {
24801                mIsolatedOwners.put(isolatedUid, ownerUid);
24802            }
24803        }
24804
24805        @Override
24806        public void removeIsolatedUid(int isolatedUid) {
24807            synchronized (mPackages) {
24808                mIsolatedOwners.delete(isolatedUid);
24809            }
24810        }
24811
24812        @Override
24813        public int getUidTargetSdkVersion(int uid) {
24814            synchronized (mPackages) {
24815                return getUidTargetSdkVersionLockedLPr(uid);
24816            }
24817        }
24818
24819        @Override
24820        public boolean canAccessInstantApps(int callingUid, int userId) {
24821            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24822        }
24823    }
24824
24825    @Override
24826    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24827        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24828        synchronized (mPackages) {
24829            final long identity = Binder.clearCallingIdentity();
24830            try {
24831                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
24832                        packageNames, userId);
24833            } finally {
24834                Binder.restoreCallingIdentity(identity);
24835            }
24836        }
24837    }
24838
24839    @Override
24840    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24841        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24842        synchronized (mPackages) {
24843            final long identity = Binder.clearCallingIdentity();
24844            try {
24845                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
24846                        packageNames, userId);
24847            } finally {
24848                Binder.restoreCallingIdentity(identity);
24849            }
24850        }
24851    }
24852
24853    private static void enforceSystemOrPhoneCaller(String tag) {
24854        int callingUid = Binder.getCallingUid();
24855        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24856            throw new SecurityException(
24857                    "Cannot call " + tag + " from UID " + callingUid);
24858        }
24859    }
24860
24861    boolean isHistoricalPackageUsageAvailable() {
24862        return mPackageUsage.isHistoricalPackageUsageAvailable();
24863    }
24864
24865    /**
24866     * Return a <b>copy</b> of the collection of packages known to the package manager.
24867     * @return A copy of the values of mPackages.
24868     */
24869    Collection<PackageParser.Package> getPackages() {
24870        synchronized (mPackages) {
24871            return new ArrayList<>(mPackages.values());
24872        }
24873    }
24874
24875    /**
24876     * Logs process start information (including base APK hash) to the security log.
24877     * @hide
24878     */
24879    @Override
24880    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24881            String apkFile, int pid) {
24882        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24883            return;
24884        }
24885        if (!SecurityLog.isLoggingEnabled()) {
24886            return;
24887        }
24888        Bundle data = new Bundle();
24889        data.putLong("startTimestamp", System.currentTimeMillis());
24890        data.putString("processName", processName);
24891        data.putInt("uid", uid);
24892        data.putString("seinfo", seinfo);
24893        data.putString("apkFile", apkFile);
24894        data.putInt("pid", pid);
24895        Message msg = mProcessLoggingHandler.obtainMessage(
24896                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24897        msg.setData(data);
24898        mProcessLoggingHandler.sendMessage(msg);
24899    }
24900
24901    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24902        return mCompilerStats.getPackageStats(pkgName);
24903    }
24904
24905    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24906        return getOrCreateCompilerPackageStats(pkg.packageName);
24907    }
24908
24909    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24910        return mCompilerStats.getOrCreatePackageStats(pkgName);
24911    }
24912
24913    public void deleteCompilerPackageStats(String pkgName) {
24914        mCompilerStats.deletePackageStats(pkgName);
24915    }
24916
24917    @Override
24918    public int getInstallReason(String packageName, int userId) {
24919        final int callingUid = Binder.getCallingUid();
24920        enforceCrossUserPermission(callingUid, userId,
24921                true /* requireFullPermission */, false /* checkShell */,
24922                "get install reason");
24923        synchronized (mPackages) {
24924            final PackageSetting ps = mSettings.mPackages.get(packageName);
24925            if (filterAppAccessLPr(ps, callingUid, userId)) {
24926                return PackageManager.INSTALL_REASON_UNKNOWN;
24927            }
24928            if (ps != null) {
24929                return ps.getInstallReason(userId);
24930            }
24931        }
24932        return PackageManager.INSTALL_REASON_UNKNOWN;
24933    }
24934
24935    @Override
24936    public boolean canRequestPackageInstalls(String packageName, int userId) {
24937        return canRequestPackageInstallsInternal(packageName, 0, userId,
24938                true /* throwIfPermNotDeclared*/);
24939    }
24940
24941    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24942            boolean throwIfPermNotDeclared) {
24943        int callingUid = Binder.getCallingUid();
24944        int uid = getPackageUid(packageName, 0, userId);
24945        if (callingUid != uid && callingUid != Process.ROOT_UID
24946                && callingUid != Process.SYSTEM_UID) {
24947            throw new SecurityException(
24948                    "Caller uid " + callingUid + " does not own package " + packageName);
24949        }
24950        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24951        if (info == null) {
24952            return false;
24953        }
24954        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24955            return false;
24956        }
24957        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24958        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24959        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24960            if (throwIfPermNotDeclared) {
24961                throw new SecurityException("Need to declare " + appOpPermission
24962                        + " to call this api");
24963            } else {
24964                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24965                return false;
24966            }
24967        }
24968        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24969            return false;
24970        }
24971        if (mExternalSourcesPolicy != null) {
24972            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24973            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24974                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24975            }
24976        }
24977        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24978    }
24979
24980    @Override
24981    public ComponentName getInstantAppResolverSettingsComponent() {
24982        return mInstantAppResolverSettingsComponent;
24983    }
24984
24985    @Override
24986    public ComponentName getInstantAppInstallerComponent() {
24987        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24988            return null;
24989        }
24990        return mInstantAppInstallerActivity == null
24991                ? null : mInstantAppInstallerActivity.getComponentName();
24992    }
24993
24994    @Override
24995    public String getInstantAppAndroidId(String packageName, int userId) {
24996        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24997                "getInstantAppAndroidId");
24998        enforceCrossUserPermission(Binder.getCallingUid(), userId,
24999                true /* requireFullPermission */, false /* checkShell */,
25000                "getInstantAppAndroidId");
25001        // Make sure the target is an Instant App.
25002        if (!isInstantApp(packageName, userId)) {
25003            return null;
25004        }
25005        synchronized (mPackages) {
25006            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25007        }
25008    }
25009
25010    boolean canHaveOatDir(String packageName) {
25011        synchronized (mPackages) {
25012            PackageParser.Package p = mPackages.get(packageName);
25013            if (p == null) {
25014                return false;
25015            }
25016            return p.canHaveOatDir();
25017        }
25018    }
25019
25020    private String getOatDir(PackageParser.Package pkg) {
25021        if (!pkg.canHaveOatDir()) {
25022            return null;
25023        }
25024        File codePath = new File(pkg.codePath);
25025        if (codePath.isDirectory()) {
25026            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25027        }
25028        return null;
25029    }
25030
25031    void deleteOatArtifactsOfPackage(String packageName) {
25032        final String[] instructionSets;
25033        final List<String> codePaths;
25034        final String oatDir;
25035        final PackageParser.Package pkg;
25036        synchronized (mPackages) {
25037            pkg = mPackages.get(packageName);
25038        }
25039        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25040        codePaths = pkg.getAllCodePaths();
25041        oatDir = getOatDir(pkg);
25042
25043        for (String codePath : codePaths) {
25044            for (String isa : instructionSets) {
25045                try {
25046                    mInstaller.deleteOdex(codePath, isa, oatDir);
25047                } catch (InstallerException e) {
25048                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25049                }
25050            }
25051        }
25052    }
25053
25054    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25055        Set<String> unusedPackages = new HashSet<>();
25056        long currentTimeInMillis = System.currentTimeMillis();
25057        synchronized (mPackages) {
25058            for (PackageParser.Package pkg : mPackages.values()) {
25059                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25060                if (ps == null) {
25061                    continue;
25062                }
25063                PackageDexUsage.PackageUseInfo packageUseInfo = getDexManager().getPackageUseInfo(
25064                        pkg.packageName);
25065                if (PackageManagerServiceUtils
25066                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25067                                downgradeTimeThresholdMillis, packageUseInfo,
25068                                pkg.getLatestPackageUseTimeInMills(),
25069                                pkg.getLatestForegroundPackageUseTimeInMills())) {
25070                    unusedPackages.add(pkg.packageName);
25071                }
25072            }
25073        }
25074        return unusedPackages;
25075    }
25076}
25077
25078interface PackageSender {
25079    void sendPackageBroadcast(final String action, final String pkg,
25080        final Bundle extras, final int flags, final String targetPkg,
25081        final IIntentReceiver finishedReceiver, final int[] userIds);
25082    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
25083        int appId, int... userIds);
25084}
25085