PackageManagerService.java revision c842393bc55509b094d3a71f164fcdbadf5c7997
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_INTERNAL;
59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
65import static android.content.pm.PackageManager.MATCH_ALL;
66import static android.content.pm.PackageManager.MATCH_ANY_USER;
67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
79import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
80import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
81import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
82import static android.content.pm.PackageManager.PERMISSION_DENIED;
83import static android.content.pm.PackageManager.PERMISSION_GRANTED;
84import static android.content.pm.PackageParser.PARSE_IS_OEM;
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.os.storage.StorageManager.FLAG_STORAGE_CE;
89import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
90import static android.system.OsConstants.O_CREAT;
91import static android.system.OsConstants.O_RDWR;
92
93import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
94import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
95import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
96import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
97import static com.android.internal.util.ArrayUtils.appendInt;
98import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
99import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
100import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
101import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
102import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
103import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
104import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
105import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE;
106import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS;
107import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
108import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
109
110import android.Manifest;
111import android.annotation.IntDef;
112import android.annotation.NonNull;
113import android.annotation.Nullable;
114import android.app.ActivityManager;
115import android.app.AppOpsManager;
116import android.app.IActivityManager;
117import android.app.ResourcesManager;
118import android.app.admin.IDevicePolicyManager;
119import android.app.admin.SecurityLog;
120import android.app.backup.IBackupManager;
121import android.content.BroadcastReceiver;
122import android.content.ComponentName;
123import android.content.ContentResolver;
124import android.content.Context;
125import android.content.IIntentReceiver;
126import android.content.Intent;
127import android.content.IntentFilter;
128import android.content.IntentSender;
129import android.content.IntentSender.SendIntentException;
130import android.content.ServiceConnection;
131import android.content.pm.ActivityInfo;
132import android.content.pm.ApplicationInfo;
133import android.content.pm.AppsQueryHelper;
134import android.content.pm.AuxiliaryResolveInfo;
135import android.content.pm.ChangedPackages;
136import android.content.pm.ComponentInfo;
137import android.content.pm.FallbackCategoryProvider;
138import android.content.pm.FeatureInfo;
139import android.content.pm.IDexModuleRegisterCallback;
140import android.content.pm.IOnPermissionsChangeListener;
141import android.content.pm.IPackageDataObserver;
142import android.content.pm.IPackageDeleteObserver;
143import android.content.pm.IPackageDeleteObserver2;
144import android.content.pm.IPackageInstallObserver2;
145import android.content.pm.IPackageInstaller;
146import android.content.pm.IPackageManager;
147import android.content.pm.IPackageManagerNative;
148import android.content.pm.IPackageMoveObserver;
149import android.content.pm.IPackageStatsObserver;
150import android.content.pm.InstantAppInfo;
151import android.content.pm.InstantAppRequest;
152import android.content.pm.InstantAppResolveInfo;
153import android.content.pm.InstrumentationInfo;
154import android.content.pm.IntentFilterVerificationInfo;
155import android.content.pm.KeySet;
156import android.content.pm.PackageCleanItem;
157import android.content.pm.PackageInfo;
158import android.content.pm.PackageInfoLite;
159import android.content.pm.PackageInstaller;
160import android.content.pm.PackageManager;
161import android.content.pm.PackageManagerInternal;
162import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
163import android.content.pm.PackageParser;
164import android.content.pm.PackageParser.ActivityIntentInfo;
165import android.content.pm.PackageParser.Package;
166import android.content.pm.PackageParser.PackageLite;
167import android.content.pm.PackageParser.PackageParserException;
168import android.content.pm.PackageStats;
169import android.content.pm.PackageUserState;
170import android.content.pm.ParceledListSlice;
171import android.content.pm.PermissionGroupInfo;
172import android.content.pm.PermissionInfo;
173import android.content.pm.ProviderInfo;
174import android.content.pm.ResolveInfo;
175import android.content.pm.ServiceInfo;
176import android.content.pm.SharedLibraryInfo;
177import android.content.pm.Signature;
178import android.content.pm.UserInfo;
179import android.content.pm.VerifierDeviceIdentity;
180import android.content.pm.VerifierInfo;
181import android.content.pm.VersionedPackage;
182import android.content.res.Resources;
183import android.database.ContentObserver;
184import android.graphics.Bitmap;
185import android.hardware.display.DisplayManager;
186import android.net.Uri;
187import android.os.Binder;
188import android.os.Build;
189import android.os.Bundle;
190import android.os.Debug;
191import android.os.Environment;
192import android.os.Environment.UserEnvironment;
193import android.os.FileUtils;
194import android.os.Handler;
195import android.os.IBinder;
196import android.os.Looper;
197import android.os.Message;
198import android.os.Parcel;
199import android.os.ParcelFileDescriptor;
200import android.os.PatternMatcher;
201import android.os.Process;
202import android.os.RemoteCallbackList;
203import android.os.RemoteException;
204import android.os.ResultReceiver;
205import android.os.SELinux;
206import android.os.ServiceManager;
207import android.os.ShellCallback;
208import android.os.SystemClock;
209import android.os.SystemProperties;
210import android.os.Trace;
211import android.os.UserHandle;
212import android.os.UserManager;
213import android.os.UserManagerInternal;
214import android.os.storage.IStorageManager;
215import android.os.storage.StorageEventListener;
216import android.os.storage.StorageManager;
217import android.os.storage.StorageManagerInternal;
218import android.os.storage.VolumeInfo;
219import android.os.storage.VolumeRecord;
220import android.provider.Settings.Global;
221import android.provider.Settings.Secure;
222import android.security.KeyStore;
223import android.security.SystemKeyStore;
224import android.service.pm.PackageServiceDumpProto;
225import android.system.ErrnoException;
226import android.system.Os;
227import android.text.TextUtils;
228import android.text.format.DateUtils;
229import android.util.ArrayMap;
230import android.util.ArraySet;
231import android.util.Base64;
232import android.util.DisplayMetrics;
233import android.util.EventLog;
234import android.util.ExceptionUtils;
235import android.util.Log;
236import android.util.LogPrinter;
237import android.util.MathUtils;
238import android.util.PackageUtils;
239import android.util.Pair;
240import android.util.PrintStreamPrinter;
241import android.util.Slog;
242import android.util.SparseArray;
243import android.util.SparseBooleanArray;
244import android.util.SparseIntArray;
245import android.util.TimingsTraceLog;
246import android.util.Xml;
247import android.util.jar.StrictJarFile;
248import android.util.proto.ProtoOutputStream;
249import android.view.Display;
250
251import com.android.internal.R;
252import com.android.internal.annotations.GuardedBy;
253import com.android.internal.app.IMediaContainerService;
254import com.android.internal.app.ResolverActivity;
255import com.android.internal.content.NativeLibraryHelper;
256import com.android.internal.content.PackageHelper;
257import com.android.internal.logging.MetricsLogger;
258import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
259import com.android.internal.os.IParcelFileDescriptorFactory;
260import com.android.internal.os.RoSystemProperties;
261import com.android.internal.os.SomeArgs;
262import com.android.internal.os.Zygote;
263import com.android.internal.telephony.CarrierAppUtils;
264import com.android.internal.util.ArrayUtils;
265import com.android.internal.util.ConcurrentUtils;
266import com.android.internal.util.DumpUtils;
267import com.android.internal.util.FastPrintWriter;
268import com.android.internal.util.FastXmlSerializer;
269import com.android.internal.util.IndentingPrintWriter;
270import com.android.internal.util.Preconditions;
271import com.android.internal.util.XmlUtils;
272import com.android.server.AttributeCache;
273import com.android.server.DeviceIdleController;
274import com.android.server.EventLogTags;
275import com.android.server.FgThread;
276import com.android.server.IntentResolver;
277import com.android.server.LocalServices;
278import com.android.server.LockGuard;
279import com.android.server.ServiceThread;
280import com.android.server.SystemConfig;
281import com.android.server.SystemServerInitThreadPool;
282import com.android.server.Watchdog;
283import com.android.server.net.NetworkPolicyManagerInternal;
284import com.android.server.pm.Installer.InstallerException;
285import com.android.server.pm.Settings.DatabaseVersion;
286import com.android.server.pm.Settings.VersionInfo;
287import com.android.server.pm.dex.DexManager;
288import com.android.server.pm.dex.DexoptOptions;
289import com.android.server.pm.dex.PackageDexUsage;
290import com.android.server.pm.permission.BasePermission;
291import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
292import com.android.server.pm.permission.PermissionManagerService;
293import com.android.server.pm.permission.PermissionManagerInternal;
294import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
295import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
296import com.android.server.pm.permission.PermissionsState;
297import com.android.server.pm.permission.PermissionsState.PermissionState;
298import com.android.server.storage.DeviceStorageMonitorInternal;
299
300import dalvik.system.CloseGuard;
301import dalvik.system.DexFile;
302import dalvik.system.VMRuntime;
303
304import libcore.io.IoUtils;
305import libcore.io.Streams;
306import libcore.util.EmptyArray;
307
308import org.xmlpull.v1.XmlPullParser;
309import org.xmlpull.v1.XmlPullParserException;
310import org.xmlpull.v1.XmlSerializer;
311
312import java.io.BufferedOutputStream;
313import java.io.BufferedReader;
314import java.io.ByteArrayInputStream;
315import java.io.ByteArrayOutputStream;
316import java.io.File;
317import java.io.FileDescriptor;
318import java.io.FileInputStream;
319import java.io.FileOutputStream;
320import java.io.FileReader;
321import java.io.FilenameFilter;
322import java.io.IOException;
323import java.io.InputStream;
324import java.io.OutputStream;
325import java.io.PrintWriter;
326import java.lang.annotation.Retention;
327import java.lang.annotation.RetentionPolicy;
328import java.nio.charset.StandardCharsets;
329import java.security.DigestInputStream;
330import java.security.MessageDigest;
331import java.security.NoSuchAlgorithmException;
332import java.security.PublicKey;
333import java.security.SecureRandom;
334import java.security.cert.Certificate;
335import java.security.cert.CertificateEncodingException;
336import java.security.cert.CertificateException;
337import java.text.SimpleDateFormat;
338import java.util.ArrayList;
339import java.util.Arrays;
340import java.util.Collection;
341import java.util.Collections;
342import java.util.Comparator;
343import java.util.Date;
344import java.util.HashMap;
345import java.util.HashSet;
346import java.util.Iterator;
347import java.util.List;
348import java.util.Map;
349import java.util.Objects;
350import java.util.Set;
351import java.util.concurrent.CountDownLatch;
352import java.util.concurrent.Future;
353import java.util.concurrent.TimeUnit;
354import java.util.concurrent.atomic.AtomicBoolean;
355import java.util.concurrent.atomic.AtomicInteger;
356import java.util.zip.GZIPInputStream;
357
358/**
359 * Keep track of all those APKs everywhere.
360 * <p>
361 * Internally there are two important locks:
362 * <ul>
363 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
364 * and other related state. It is a fine-grained lock that should only be held
365 * momentarily, as it's one of the most contended locks in the system.
366 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
367 * operations typically involve heavy lifting of application data on disk. Since
368 * {@code installd} is single-threaded, and it's operations can often be slow,
369 * this lock should never be acquired while already holding {@link #mPackages}.
370 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
371 * holding {@link #mInstallLock}.
372 * </ul>
373 * Many internal methods rely on the caller to hold the appropriate locks, and
374 * this contract is expressed through method name suffixes:
375 * <ul>
376 * <li>fooLI(): the caller must hold {@link #mInstallLock}
377 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
378 * being modified must be frozen
379 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
380 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
381 * </ul>
382 * <p>
383 * Because this class is very central to the platform's security; please run all
384 * CTS and unit tests whenever making modifications:
385 *
386 * <pre>
387 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
388 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
389 * </pre>
390 */
391public class PackageManagerService extends IPackageManager.Stub
392        implements PackageSender {
393    static final String TAG = "PackageManager";
394    public static final boolean DEBUG_SETTINGS = false;
395    static final boolean DEBUG_PREFERRED = false;
396    static final boolean DEBUG_UPGRADE = false;
397    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
398    private static final boolean DEBUG_BACKUP = false;
399    private static final boolean DEBUG_INSTALL = false;
400    public static final boolean DEBUG_REMOVE = false;
401    private static final boolean DEBUG_BROADCASTS = false;
402    private static final boolean DEBUG_SHOW_INFO = false;
403    private static final boolean DEBUG_PACKAGE_INFO = false;
404    private static final boolean DEBUG_INTENT_MATCHING = false;
405    public static final boolean DEBUG_PACKAGE_SCANNING = false;
406    private static final boolean DEBUG_VERIFY = false;
407    private static final boolean DEBUG_FILTERS = false;
408    public static final boolean DEBUG_PERMISSIONS = false;
409    private static final boolean DEBUG_SHARED_LIBRARIES = false;
410    private static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
411
412    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
413    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
414    // user, but by default initialize to this.
415    public static final boolean DEBUG_DEXOPT = false;
416
417    private static final boolean DEBUG_ABI_SELECTION = false;
418    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
419    private static final boolean DEBUG_TRIAGED_MISSING = false;
420    private static final boolean DEBUG_APP_DATA = false;
421
422    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
423    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
424
425    private static final boolean HIDE_EPHEMERAL_APIS = false;
426
427    private static final boolean ENABLE_FREE_CACHE_V2 =
428            SystemProperties.getBoolean("fw.free_cache_v2", true);
429
430    private static final int RADIO_UID = Process.PHONE_UID;
431    private static final int LOG_UID = Process.LOG_UID;
432    private static final int NFC_UID = Process.NFC_UID;
433    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
434    private static final int SHELL_UID = Process.SHELL_UID;
435
436    // Suffix used during package installation when copying/moving
437    // package apks to install directory.
438    private static final String INSTALL_PACKAGE_SUFFIX = "-";
439
440    static final int SCAN_NO_DEX = 1<<1;
441    static final int SCAN_FORCE_DEX = 1<<2;
442    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
443    static final int SCAN_NEW_INSTALL = 1<<4;
444    static final int SCAN_UPDATE_TIME = 1<<5;
445    static final int SCAN_BOOTING = 1<<6;
446    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
447    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
448    static final int SCAN_REPLACING = 1<<9;
449    static final int SCAN_REQUIRE_KNOWN = 1<<10;
450    static final int SCAN_MOVE = 1<<11;
451    static final int SCAN_INITIAL = 1<<12;
452    static final int SCAN_CHECK_ONLY = 1<<13;
453    static final int SCAN_DONT_KILL_APP = 1<<14;
454    static final int SCAN_IGNORE_FROZEN = 1<<15;
455    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
456    static final int SCAN_AS_INSTANT_APP = 1<<17;
457    static final int SCAN_AS_FULL_APP = 1<<18;
458    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<19;
459    /** Should not be with the scan flags */
460    static final int FLAGS_REMOVE_CHATTY = 1<<31;
461
462    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
463    /** Extension of the compressed packages */
464    private final static String COMPRESSED_EXTENSION = ".gz";
465    /** Suffix of stub packages on the system partition */
466    private final static String STUB_SUFFIX = "-Stub";
467
468    private static final int[] EMPTY_INT_ARRAY = new int[0];
469
470    private static final int TYPE_UNKNOWN = 0;
471    private static final int TYPE_ACTIVITY = 1;
472    private static final int TYPE_RECEIVER = 2;
473    private static final int TYPE_SERVICE = 3;
474    private static final int TYPE_PROVIDER = 4;
475    @IntDef(prefix = { "TYPE_" }, value = {
476            TYPE_UNKNOWN,
477            TYPE_ACTIVITY,
478            TYPE_RECEIVER,
479            TYPE_SERVICE,
480            TYPE_PROVIDER,
481    })
482    @Retention(RetentionPolicy.SOURCE)
483    public @interface ComponentType {}
484
485    /**
486     * Timeout (in milliseconds) after which the watchdog should declare that
487     * our handler thread is wedged.  The usual default for such things is one
488     * minute but we sometimes do very lengthy I/O operations on this thread,
489     * such as installing multi-gigabyte applications, so ours needs to be longer.
490     */
491    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
492
493    /**
494     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
495     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
496     * settings entry if available, otherwise we use the hardcoded default.  If it's been
497     * more than this long since the last fstrim, we force one during the boot sequence.
498     *
499     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
500     * one gets run at the next available charging+idle time.  This final mandatory
501     * no-fstrim check kicks in only of the other scheduling criteria is never met.
502     */
503    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
504
505    /**
506     * Whether verification is enabled by default.
507     */
508    private static final boolean DEFAULT_VERIFY_ENABLE = true;
509
510    /**
511     * The default maximum time to wait for the verification agent to return in
512     * milliseconds.
513     */
514    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
515
516    /**
517     * The default response for package verification timeout.
518     *
519     * This can be either PackageManager.VERIFICATION_ALLOW or
520     * PackageManager.VERIFICATION_REJECT.
521     */
522    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
523
524    static final String PLATFORM_PACKAGE_NAME = "android";
525
526    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
527
528    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
529            DEFAULT_CONTAINER_PACKAGE,
530            "com.android.defcontainer.DefaultContainerService");
531
532    private static final String KILL_APP_REASON_GIDS_CHANGED =
533            "permission grant or revoke changed gids";
534
535    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
536            "permissions revoked";
537
538    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
539
540    private static final String PACKAGE_SCHEME = "package";
541
542    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
543
544    /** Permission grant: not grant the permission. */
545    private static final int GRANT_DENIED = 1;
546
547    /** Permission grant: grant the permission as an install permission. */
548    private static final int GRANT_INSTALL = 2;
549
550    /** Permission grant: grant the permission as a runtime one. */
551    private static final int GRANT_RUNTIME = 3;
552
553    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
554    private static final int GRANT_UPGRADE = 4;
555
556    /** Canonical intent used to identify what counts as a "web browser" app */
557    private static final Intent sBrowserIntent;
558    static {
559        sBrowserIntent = new Intent();
560        sBrowserIntent.setAction(Intent.ACTION_VIEW);
561        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
562        sBrowserIntent.setData(Uri.parse("http:"));
563    }
564
565    /**
566     * The set of all protected actions [i.e. those actions for which a high priority
567     * intent filter is disallowed].
568     */
569    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
570    static {
571        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
572        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
573        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
574        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
575    }
576
577    // Compilation reasons.
578    public static final int REASON_FIRST_BOOT = 0;
579    public static final int REASON_BOOT = 1;
580    public static final int REASON_INSTALL = 2;
581    public static final int REASON_BACKGROUND_DEXOPT = 3;
582    public static final int REASON_AB_OTA = 4;
583    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
584    public static final int REASON_SHARED = 6;
585
586    public static final int REASON_LAST = REASON_SHARED;
587
588    /** All dangerous permission names in the same order as the events in MetricsEvent */
589    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
590            Manifest.permission.READ_CALENDAR,
591            Manifest.permission.WRITE_CALENDAR,
592            Manifest.permission.CAMERA,
593            Manifest.permission.READ_CONTACTS,
594            Manifest.permission.WRITE_CONTACTS,
595            Manifest.permission.GET_ACCOUNTS,
596            Manifest.permission.ACCESS_FINE_LOCATION,
597            Manifest.permission.ACCESS_COARSE_LOCATION,
598            Manifest.permission.RECORD_AUDIO,
599            Manifest.permission.READ_PHONE_STATE,
600            Manifest.permission.CALL_PHONE,
601            Manifest.permission.READ_CALL_LOG,
602            Manifest.permission.WRITE_CALL_LOG,
603            Manifest.permission.ADD_VOICEMAIL,
604            Manifest.permission.USE_SIP,
605            Manifest.permission.PROCESS_OUTGOING_CALLS,
606            Manifest.permission.READ_CELL_BROADCASTS,
607            Manifest.permission.BODY_SENSORS,
608            Manifest.permission.SEND_SMS,
609            Manifest.permission.RECEIVE_SMS,
610            Manifest.permission.READ_SMS,
611            Manifest.permission.RECEIVE_WAP_PUSH,
612            Manifest.permission.RECEIVE_MMS,
613            Manifest.permission.READ_EXTERNAL_STORAGE,
614            Manifest.permission.WRITE_EXTERNAL_STORAGE,
615            Manifest.permission.READ_PHONE_NUMBERS,
616            Manifest.permission.ANSWER_PHONE_CALLS);
617
618
619    /**
620     * Version number for the package parser cache. Increment this whenever the format or
621     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
622     */
623    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
624
625    /**
626     * Whether the package parser cache is enabled.
627     */
628    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
629
630    final ServiceThread mHandlerThread;
631
632    final PackageHandler mHandler;
633
634    private final ProcessLoggingHandler mProcessLoggingHandler;
635
636    /**
637     * Messages for {@link #mHandler} that need to wait for system ready before
638     * being dispatched.
639     */
640    private ArrayList<Message> mPostSystemReadyMessages;
641
642    final int mSdkVersion = Build.VERSION.SDK_INT;
643
644    final Context mContext;
645    final boolean mFactoryTest;
646    final boolean mOnlyCore;
647    final DisplayMetrics mMetrics;
648    final int mDefParseFlags;
649    final String[] mSeparateProcesses;
650    final boolean mIsUpgrade;
651    final boolean mIsPreNUpgrade;
652    final boolean mIsPreNMR1Upgrade;
653
654    // Have we told the Activity Manager to whitelist the default container service by uid yet?
655    @GuardedBy("mPackages")
656    boolean mDefaultContainerWhitelisted = false;
657
658    @GuardedBy("mPackages")
659    private boolean mDexOptDialogShown;
660
661    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
662    // LOCK HELD.  Can be called with mInstallLock held.
663    @GuardedBy("mInstallLock")
664    final Installer mInstaller;
665
666    /** Directory where installed third-party apps stored */
667    final File mAppInstallDir;
668
669    /**
670     * Directory to which applications installed internally have their
671     * 32 bit native libraries copied.
672     */
673    private File mAppLib32InstallDir;
674
675    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
676    // apps.
677    final File mDrmAppPrivateInstallDir;
678
679    // ----------------------------------------------------------------
680
681    // Lock for state used when installing and doing other long running
682    // operations.  Methods that must be called with this lock held have
683    // the suffix "LI".
684    final Object mInstallLock = new Object();
685
686    // ----------------------------------------------------------------
687
688    // Keys are String (package name), values are Package.  This also serves
689    // as the lock for the global state.  Methods that must be called with
690    // this lock held have the prefix "LP".
691    @GuardedBy("mPackages")
692    final ArrayMap<String, PackageParser.Package> mPackages =
693            new ArrayMap<String, PackageParser.Package>();
694
695    final ArrayMap<String, Set<String>> mKnownCodebase =
696            new ArrayMap<String, Set<String>>();
697
698    // Keys are isolated uids and values are the uid of the application
699    // that created the isolated proccess.
700    @GuardedBy("mPackages")
701    final SparseIntArray mIsolatedOwners = new SparseIntArray();
702
703    /**
704     * Tracks new system packages [received in an OTA] that we expect to
705     * find updated user-installed versions. Keys are package name, values
706     * are package location.
707     */
708    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
709    /**
710     * Tracks high priority intent filters for protected actions. During boot, certain
711     * filter actions are protected and should never be allowed to have a high priority
712     * intent filter for them. However, there is one, and only one exception -- the
713     * setup wizard. It must be able to define a high priority intent filter for these
714     * actions to ensure there are no escapes from the wizard. We need to delay processing
715     * of these during boot as we need to look at all of the system packages in order
716     * to know which component is the setup wizard.
717     */
718    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
719    /**
720     * Whether or not processing protected filters should be deferred.
721     */
722    private boolean mDeferProtectedFilters = true;
723
724    /**
725     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
726     */
727    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
728    /**
729     * Whether or not system app permissions should be promoted from install to runtime.
730     */
731    boolean mPromoteSystemApps;
732
733    @GuardedBy("mPackages")
734    final Settings mSettings;
735
736    /**
737     * Set of package names that are currently "frozen", which means active
738     * surgery is being done on the code/data for that package. The platform
739     * will refuse to launch frozen packages to avoid race conditions.
740     *
741     * @see PackageFreezer
742     */
743    @GuardedBy("mPackages")
744    final ArraySet<String> mFrozenPackages = new ArraySet<>();
745
746    final ProtectedPackages mProtectedPackages;
747
748    @GuardedBy("mLoadedVolumes")
749    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
750
751    boolean mFirstBoot;
752
753    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
754
755    // System configuration read by SystemConfig.
756    final int[] mGlobalGids;
757    final SparseArray<ArraySet<String>> mSystemPermissions;
758    @GuardedBy("mAvailableFeatures")
759    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
760
761    // If mac_permissions.xml was found for seinfo labeling.
762    boolean mFoundPolicyFile;
763
764    private final InstantAppRegistry mInstantAppRegistry;
765
766    @GuardedBy("mPackages")
767    int mChangedPackagesSequenceNumber;
768    /**
769     * List of changed [installed, removed or updated] packages.
770     * mapping from user id -> sequence number -> package name
771     */
772    @GuardedBy("mPackages")
773    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
774    /**
775     * The sequence number of the last change to a package.
776     * mapping from user id -> package name -> sequence number
777     */
778    @GuardedBy("mPackages")
779    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
780
781    class PackageParserCallback implements PackageParser.Callback {
782        @Override public final boolean hasFeature(String feature) {
783            return PackageManagerService.this.hasSystemFeature(feature, 0);
784        }
785
786        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
787                Collection<PackageParser.Package> allPackages, String targetPackageName) {
788            List<PackageParser.Package> overlayPackages = null;
789            for (PackageParser.Package p : allPackages) {
790                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
791                    if (overlayPackages == null) {
792                        overlayPackages = new ArrayList<PackageParser.Package>();
793                    }
794                    overlayPackages.add(p);
795                }
796            }
797            if (overlayPackages != null) {
798                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
799                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
800                        return p1.mOverlayPriority - p2.mOverlayPriority;
801                    }
802                };
803                Collections.sort(overlayPackages, cmp);
804            }
805            return overlayPackages;
806        }
807
808        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
809                String targetPackageName, String targetPath) {
810            if ("android".equals(targetPackageName)) {
811                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
812                // native AssetManager.
813                return null;
814            }
815            List<PackageParser.Package> overlayPackages =
816                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
817            if (overlayPackages == null || overlayPackages.isEmpty()) {
818                return null;
819            }
820            List<String> overlayPathList = null;
821            for (PackageParser.Package overlayPackage : overlayPackages) {
822                if (targetPath == null) {
823                    if (overlayPathList == null) {
824                        overlayPathList = new ArrayList<String>();
825                    }
826                    overlayPathList.add(overlayPackage.baseCodePath);
827                    continue;
828                }
829
830                try {
831                    // Creates idmaps for system to parse correctly the Android manifest of the
832                    // target package.
833                    //
834                    // OverlayManagerService will update each of them with a correct gid from its
835                    // target package app id.
836                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
837                            UserHandle.getSharedAppGid(
838                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
839                    if (overlayPathList == null) {
840                        overlayPathList = new ArrayList<String>();
841                    }
842                    overlayPathList.add(overlayPackage.baseCodePath);
843                } catch (InstallerException e) {
844                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
845                            overlayPackage.baseCodePath);
846                }
847            }
848            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
849        }
850
851        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
852            synchronized (mPackages) {
853                return getStaticOverlayPathsLocked(
854                        mPackages.values(), targetPackageName, targetPath);
855            }
856        }
857
858        @Override public final String[] getOverlayApks(String targetPackageName) {
859            return getStaticOverlayPaths(targetPackageName, null);
860        }
861
862        @Override public final String[] getOverlayPaths(String targetPackageName,
863                String targetPath) {
864            return getStaticOverlayPaths(targetPackageName, targetPath);
865        }
866    }
867
868    class ParallelPackageParserCallback extends PackageParserCallback {
869        List<PackageParser.Package> mOverlayPackages = null;
870
871        void findStaticOverlayPackages() {
872            synchronized (mPackages) {
873                for (PackageParser.Package p : mPackages.values()) {
874                    if (p.mIsStaticOverlay) {
875                        if (mOverlayPackages == null) {
876                            mOverlayPackages = new ArrayList<PackageParser.Package>();
877                        }
878                        mOverlayPackages.add(p);
879                    }
880                }
881            }
882        }
883
884        @Override
885        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
886            // We can trust mOverlayPackages without holding mPackages because package uninstall
887            // can't happen while running parallel parsing.
888            // Moreover holding mPackages on each parsing thread causes dead-lock.
889            return mOverlayPackages == null ? null :
890                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
891        }
892    }
893
894    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
895    final ParallelPackageParserCallback mParallelPackageParserCallback =
896            new ParallelPackageParserCallback();
897
898    public static final class SharedLibraryEntry {
899        public final @Nullable String path;
900        public final @Nullable String apk;
901        public final @NonNull SharedLibraryInfo info;
902
903        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
904                String declaringPackageName, int declaringPackageVersionCode) {
905            path = _path;
906            apk = _apk;
907            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
908                    declaringPackageName, declaringPackageVersionCode), null);
909        }
910    }
911
912    // Currently known shared libraries.
913    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
914    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
915            new ArrayMap<>();
916
917    // All available activities, for your resolving pleasure.
918    final ActivityIntentResolver mActivities =
919            new ActivityIntentResolver();
920
921    // All available receivers, for your resolving pleasure.
922    final ActivityIntentResolver mReceivers =
923            new ActivityIntentResolver();
924
925    // All available services, for your resolving pleasure.
926    final ServiceIntentResolver mServices = new ServiceIntentResolver();
927
928    // All available providers, for your resolving pleasure.
929    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
930
931    // Mapping from provider base names (first directory in content URI codePath)
932    // to the provider information.
933    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
934            new ArrayMap<String, PackageParser.Provider>();
935
936    // Mapping from instrumentation class names to info about them.
937    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
938            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
939
940    // Mapping from permission names to info about them.
941    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
942            new ArrayMap<String, PackageParser.PermissionGroup>();
943
944    // Packages whose data we have transfered into another package, thus
945    // should no longer exist.
946    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
947
948    // Broadcast actions that are only available to the system.
949    @GuardedBy("mProtectedBroadcasts")
950    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
951
952    /** List of packages waiting for verification. */
953    final SparseArray<PackageVerificationState> mPendingVerification
954            = new SparseArray<PackageVerificationState>();
955
956    final PackageInstallerService mInstallerService;
957
958    private final PackageDexOptimizer mPackageDexOptimizer;
959    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
960    // is used by other apps).
961    private final DexManager mDexManager;
962
963    private AtomicInteger mNextMoveId = new AtomicInteger();
964    private final MoveCallbacks mMoveCallbacks;
965
966    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
967
968    // Cache of users who need badging.
969    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
970
971    /** Token for keys in mPendingVerification. */
972    private int mPendingVerificationToken = 0;
973
974    volatile boolean mSystemReady;
975    volatile boolean mSafeMode;
976    volatile boolean mHasSystemUidErrors;
977    private volatile boolean mEphemeralAppsDisabled;
978
979    ApplicationInfo mAndroidApplication;
980    final ActivityInfo mResolveActivity = new ActivityInfo();
981    final ResolveInfo mResolveInfo = new ResolveInfo();
982    ComponentName mResolveComponentName;
983    PackageParser.Package mPlatformPackage;
984    ComponentName mCustomResolverComponentName;
985
986    boolean mResolverReplaced = false;
987
988    private final @Nullable ComponentName mIntentFilterVerifierComponent;
989    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
990
991    private int mIntentFilterVerificationToken = 0;
992
993    /** The service connection to the ephemeral resolver */
994    final EphemeralResolverConnection mInstantAppResolverConnection;
995    /** Component used to show resolver settings for Instant Apps */
996    final ComponentName mInstantAppResolverSettingsComponent;
997
998    /** Activity used to install instant applications */
999    ActivityInfo mInstantAppInstallerActivity;
1000    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
1001
1002    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1003            = new SparseArray<IntentFilterVerificationState>();
1004
1005    // TODO remove this and go through mPermissonManager directly
1006    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1007    private final PermissionManagerInternal mPermissionManager;
1008
1009    // List of packages names to keep cached, even if they are uninstalled for all users
1010    private List<String> mKeepUninstalledPackages;
1011
1012    private UserManagerInternal mUserManagerInternal;
1013
1014    private DeviceIdleController.LocalService mDeviceIdleController;
1015
1016    private File mCacheDir;
1017
1018    private ArraySet<String> mPrivappPermissionsViolations;
1019
1020    private Future<?> mPrepareAppDataFuture;
1021
1022    private static class IFVerificationParams {
1023        PackageParser.Package pkg;
1024        boolean replacing;
1025        int userId;
1026        int verifierUid;
1027
1028        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1029                int _userId, int _verifierUid) {
1030            pkg = _pkg;
1031            replacing = _replacing;
1032            userId = _userId;
1033            replacing = _replacing;
1034            verifierUid = _verifierUid;
1035        }
1036    }
1037
1038    private interface IntentFilterVerifier<T extends IntentFilter> {
1039        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1040                                               T filter, String packageName);
1041        void startVerifications(int userId);
1042        void receiveVerificationResponse(int verificationId);
1043    }
1044
1045    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1046        private Context mContext;
1047        private ComponentName mIntentFilterVerifierComponent;
1048        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1049
1050        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1051            mContext = context;
1052            mIntentFilterVerifierComponent = verifierComponent;
1053        }
1054
1055        private String getDefaultScheme() {
1056            return IntentFilter.SCHEME_HTTPS;
1057        }
1058
1059        @Override
1060        public void startVerifications(int userId) {
1061            // Launch verifications requests
1062            int count = mCurrentIntentFilterVerifications.size();
1063            for (int n=0; n<count; n++) {
1064                int verificationId = mCurrentIntentFilterVerifications.get(n);
1065                final IntentFilterVerificationState ivs =
1066                        mIntentFilterVerificationStates.get(verificationId);
1067
1068                String packageName = ivs.getPackageName();
1069
1070                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1071                final int filterCount = filters.size();
1072                ArraySet<String> domainsSet = new ArraySet<>();
1073                for (int m=0; m<filterCount; m++) {
1074                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1075                    domainsSet.addAll(filter.getHostsList());
1076                }
1077                synchronized (mPackages) {
1078                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1079                            packageName, domainsSet) != null) {
1080                        scheduleWriteSettingsLocked();
1081                    }
1082                }
1083                sendVerificationRequest(verificationId, ivs);
1084            }
1085            mCurrentIntentFilterVerifications.clear();
1086        }
1087
1088        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1089            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1090            verificationIntent.putExtra(
1091                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1092                    verificationId);
1093            verificationIntent.putExtra(
1094                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1095                    getDefaultScheme());
1096            verificationIntent.putExtra(
1097                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1098                    ivs.getHostsString());
1099            verificationIntent.putExtra(
1100                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1101                    ivs.getPackageName());
1102            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1103            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1104
1105            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1106            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1107                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1108                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1109
1110            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1111            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1112                    "Sending IntentFilter verification broadcast");
1113        }
1114
1115        public void receiveVerificationResponse(int verificationId) {
1116            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1117
1118            final boolean verified = ivs.isVerified();
1119
1120            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1121            final int count = filters.size();
1122            if (DEBUG_DOMAIN_VERIFICATION) {
1123                Slog.i(TAG, "Received verification response " + verificationId
1124                        + " for " + count + " filters, verified=" + verified);
1125            }
1126            for (int n=0; n<count; n++) {
1127                PackageParser.ActivityIntentInfo filter = filters.get(n);
1128                filter.setVerified(verified);
1129
1130                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1131                        + " verified with result:" + verified + " and hosts:"
1132                        + ivs.getHostsString());
1133            }
1134
1135            mIntentFilterVerificationStates.remove(verificationId);
1136
1137            final String packageName = ivs.getPackageName();
1138            IntentFilterVerificationInfo ivi = null;
1139
1140            synchronized (mPackages) {
1141                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1142            }
1143            if (ivi == null) {
1144                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1145                        + verificationId + " packageName:" + packageName);
1146                return;
1147            }
1148            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1149                    "Updating IntentFilterVerificationInfo for package " + packageName
1150                            +" verificationId:" + verificationId);
1151
1152            synchronized (mPackages) {
1153                if (verified) {
1154                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1155                } else {
1156                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1157                }
1158                scheduleWriteSettingsLocked();
1159
1160                final int userId = ivs.getUserId();
1161                if (userId != UserHandle.USER_ALL) {
1162                    final int userStatus =
1163                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1164
1165                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1166                    boolean needUpdate = false;
1167
1168                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1169                    // already been set by the User thru the Disambiguation dialog
1170                    switch (userStatus) {
1171                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1172                            if (verified) {
1173                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1174                            } else {
1175                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1176                            }
1177                            needUpdate = true;
1178                            break;
1179
1180                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1181                            if (verified) {
1182                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1183                                needUpdate = true;
1184                            }
1185                            break;
1186
1187                        default:
1188                            // Nothing to do
1189                    }
1190
1191                    if (needUpdate) {
1192                        mSettings.updateIntentFilterVerificationStatusLPw(
1193                                packageName, updatedStatus, userId);
1194                        scheduleWritePackageRestrictionsLocked(userId);
1195                    }
1196                }
1197            }
1198        }
1199
1200        @Override
1201        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1202                    ActivityIntentInfo filter, String packageName) {
1203            if (!hasValidDomains(filter)) {
1204                return false;
1205            }
1206            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1207            if (ivs == null) {
1208                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1209                        packageName);
1210            }
1211            if (DEBUG_DOMAIN_VERIFICATION) {
1212                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1213            }
1214            ivs.addFilter(filter);
1215            return true;
1216        }
1217
1218        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1219                int userId, int verificationId, String packageName) {
1220            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1221                    verifierUid, userId, packageName);
1222            ivs.setPendingState();
1223            synchronized (mPackages) {
1224                mIntentFilterVerificationStates.append(verificationId, ivs);
1225                mCurrentIntentFilterVerifications.add(verificationId);
1226            }
1227            return ivs;
1228        }
1229    }
1230
1231    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1232        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1233                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1234                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1235    }
1236
1237    // Set of pending broadcasts for aggregating enable/disable of components.
1238    static class PendingPackageBroadcasts {
1239        // for each user id, a map of <package name -> components within that package>
1240        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1241
1242        public PendingPackageBroadcasts() {
1243            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1244        }
1245
1246        public ArrayList<String> get(int userId, String packageName) {
1247            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1248            return packages.get(packageName);
1249        }
1250
1251        public void put(int userId, String packageName, ArrayList<String> components) {
1252            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1253            packages.put(packageName, components);
1254        }
1255
1256        public void remove(int userId, String packageName) {
1257            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1258            if (packages != null) {
1259                packages.remove(packageName);
1260            }
1261        }
1262
1263        public void remove(int userId) {
1264            mUidMap.remove(userId);
1265        }
1266
1267        public int userIdCount() {
1268            return mUidMap.size();
1269        }
1270
1271        public int userIdAt(int n) {
1272            return mUidMap.keyAt(n);
1273        }
1274
1275        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1276            return mUidMap.get(userId);
1277        }
1278
1279        public int size() {
1280            // total number of pending broadcast entries across all userIds
1281            int num = 0;
1282            for (int i = 0; i< mUidMap.size(); i++) {
1283                num += mUidMap.valueAt(i).size();
1284            }
1285            return num;
1286        }
1287
1288        public void clear() {
1289            mUidMap.clear();
1290        }
1291
1292        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1293            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1294            if (map == null) {
1295                map = new ArrayMap<String, ArrayList<String>>();
1296                mUidMap.put(userId, map);
1297            }
1298            return map;
1299        }
1300    }
1301    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1302
1303    // Service Connection to remote media container service to copy
1304    // package uri's from external media onto secure containers
1305    // or internal storage.
1306    private IMediaContainerService mContainerService = null;
1307
1308    static final int SEND_PENDING_BROADCAST = 1;
1309    static final int MCS_BOUND = 3;
1310    static final int END_COPY = 4;
1311    static final int INIT_COPY = 5;
1312    static final int MCS_UNBIND = 6;
1313    static final int START_CLEANING_PACKAGE = 7;
1314    static final int FIND_INSTALL_LOC = 8;
1315    static final int POST_INSTALL = 9;
1316    static final int MCS_RECONNECT = 10;
1317    static final int MCS_GIVE_UP = 11;
1318    static final int WRITE_SETTINGS = 13;
1319    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1320    static final int PACKAGE_VERIFIED = 15;
1321    static final int CHECK_PENDING_VERIFICATION = 16;
1322    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1323    static final int INTENT_FILTER_VERIFIED = 18;
1324    static final int WRITE_PACKAGE_LIST = 19;
1325    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1326
1327    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1328
1329    // Delay time in millisecs
1330    static final int BROADCAST_DELAY = 10 * 1000;
1331
1332    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1333            2 * 60 * 60 * 1000L; /* two hours */
1334
1335    static UserManagerService sUserManager;
1336
1337    // Stores a list of users whose package restrictions file needs to be updated
1338    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1339
1340    final private DefaultContainerConnection mDefContainerConn =
1341            new DefaultContainerConnection();
1342    class DefaultContainerConnection implements ServiceConnection {
1343        public void onServiceConnected(ComponentName name, IBinder service) {
1344            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1345            final IMediaContainerService imcs = IMediaContainerService.Stub
1346                    .asInterface(Binder.allowBlocking(service));
1347            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1348        }
1349
1350        public void onServiceDisconnected(ComponentName name) {
1351            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1352        }
1353    }
1354
1355    // Recordkeeping of restore-after-install operations that are currently in flight
1356    // between the Package Manager and the Backup Manager
1357    static class PostInstallData {
1358        public InstallArgs args;
1359        public PackageInstalledInfo res;
1360
1361        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1362            args = _a;
1363            res = _r;
1364        }
1365    }
1366
1367    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1368    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1369
1370    // XML tags for backup/restore of various bits of state
1371    private static final String TAG_PREFERRED_BACKUP = "pa";
1372    private static final String TAG_DEFAULT_APPS = "da";
1373    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1374
1375    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1376    private static final String TAG_ALL_GRANTS = "rt-grants";
1377    private static final String TAG_GRANT = "grant";
1378    private static final String ATTR_PACKAGE_NAME = "pkg";
1379
1380    private static final String TAG_PERMISSION = "perm";
1381    private static final String ATTR_PERMISSION_NAME = "name";
1382    private static final String ATTR_IS_GRANTED = "g";
1383    private static final String ATTR_USER_SET = "set";
1384    private static final String ATTR_USER_FIXED = "fixed";
1385    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1386
1387    // System/policy permission grants are not backed up
1388    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1389            FLAG_PERMISSION_POLICY_FIXED
1390            | FLAG_PERMISSION_SYSTEM_FIXED
1391            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1392
1393    // And we back up these user-adjusted states
1394    private static final int USER_RUNTIME_GRANT_MASK =
1395            FLAG_PERMISSION_USER_SET
1396            | FLAG_PERMISSION_USER_FIXED
1397            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1398
1399    final @Nullable String mRequiredVerifierPackage;
1400    final @NonNull String mRequiredInstallerPackage;
1401    final @NonNull String mRequiredUninstallerPackage;
1402    final @Nullable String mSetupWizardPackage;
1403    final @Nullable String mStorageManagerPackage;
1404    final @NonNull String mServicesSystemSharedLibraryPackageName;
1405    final @NonNull String mSharedSystemSharedLibraryPackageName;
1406
1407    final boolean mPermissionReviewRequired;
1408
1409    private final PackageUsage mPackageUsage = new PackageUsage();
1410    private final CompilerStats mCompilerStats = new CompilerStats();
1411
1412    class PackageHandler extends Handler {
1413        private boolean mBound = false;
1414        final ArrayList<HandlerParams> mPendingInstalls =
1415            new ArrayList<HandlerParams>();
1416
1417        private boolean connectToService() {
1418            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1419                    " DefaultContainerService");
1420            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1421            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1422            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1423                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1424                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1425                mBound = true;
1426                return true;
1427            }
1428            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1429            return false;
1430        }
1431
1432        private void disconnectService() {
1433            mContainerService = null;
1434            mBound = false;
1435            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1436            mContext.unbindService(mDefContainerConn);
1437            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1438        }
1439
1440        PackageHandler(Looper looper) {
1441            super(looper);
1442        }
1443
1444        public void handleMessage(Message msg) {
1445            try {
1446                doHandleMessage(msg);
1447            } finally {
1448                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1449            }
1450        }
1451
1452        void doHandleMessage(Message msg) {
1453            switch (msg.what) {
1454                case INIT_COPY: {
1455                    HandlerParams params = (HandlerParams) msg.obj;
1456                    int idx = mPendingInstalls.size();
1457                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1458                    // If a bind was already initiated we dont really
1459                    // need to do anything. The pending install
1460                    // will be processed later on.
1461                    if (!mBound) {
1462                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1463                                System.identityHashCode(mHandler));
1464                        // If this is the only one pending we might
1465                        // have to bind to the service again.
1466                        if (!connectToService()) {
1467                            Slog.e(TAG, "Failed to bind to media container service");
1468                            params.serviceError();
1469                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1470                                    System.identityHashCode(mHandler));
1471                            if (params.traceMethod != null) {
1472                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1473                                        params.traceCookie);
1474                            }
1475                            return;
1476                        } else {
1477                            // Once we bind to the service, the first
1478                            // pending request will be processed.
1479                            mPendingInstalls.add(idx, params);
1480                        }
1481                    } else {
1482                        mPendingInstalls.add(idx, params);
1483                        // Already bound to the service. Just make
1484                        // sure we trigger off processing the first request.
1485                        if (idx == 0) {
1486                            mHandler.sendEmptyMessage(MCS_BOUND);
1487                        }
1488                    }
1489                    break;
1490                }
1491                case MCS_BOUND: {
1492                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1493                    if (msg.obj != null) {
1494                        mContainerService = (IMediaContainerService) msg.obj;
1495                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1496                                System.identityHashCode(mHandler));
1497                    }
1498                    if (mContainerService == null) {
1499                        if (!mBound) {
1500                            // Something seriously wrong since we are not bound and we are not
1501                            // waiting for connection. Bail out.
1502                            Slog.e(TAG, "Cannot bind to media container service");
1503                            for (HandlerParams params : mPendingInstalls) {
1504                                // Indicate service bind error
1505                                params.serviceError();
1506                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1507                                        System.identityHashCode(params));
1508                                if (params.traceMethod != null) {
1509                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1510                                            params.traceMethod, params.traceCookie);
1511                                }
1512                                return;
1513                            }
1514                            mPendingInstalls.clear();
1515                        } else {
1516                            Slog.w(TAG, "Waiting to connect to media container service");
1517                        }
1518                    } else if (mPendingInstalls.size() > 0) {
1519                        HandlerParams params = mPendingInstalls.get(0);
1520                        if (params != null) {
1521                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1522                                    System.identityHashCode(params));
1523                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1524                            if (params.startCopy()) {
1525                                // We are done...  look for more work or to
1526                                // go idle.
1527                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1528                                        "Checking for more work or unbind...");
1529                                // Delete pending install
1530                                if (mPendingInstalls.size() > 0) {
1531                                    mPendingInstalls.remove(0);
1532                                }
1533                                if (mPendingInstalls.size() == 0) {
1534                                    if (mBound) {
1535                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1536                                                "Posting delayed MCS_UNBIND");
1537                                        removeMessages(MCS_UNBIND);
1538                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1539                                        // Unbind after a little delay, to avoid
1540                                        // continual thrashing.
1541                                        sendMessageDelayed(ubmsg, 10000);
1542                                    }
1543                                } else {
1544                                    // There are more pending requests in queue.
1545                                    // Just post MCS_BOUND message to trigger processing
1546                                    // of next pending install.
1547                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1548                                            "Posting MCS_BOUND for next work");
1549                                    mHandler.sendEmptyMessage(MCS_BOUND);
1550                                }
1551                            }
1552                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1553                        }
1554                    } else {
1555                        // Should never happen ideally.
1556                        Slog.w(TAG, "Empty queue");
1557                    }
1558                    break;
1559                }
1560                case MCS_RECONNECT: {
1561                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1562                    if (mPendingInstalls.size() > 0) {
1563                        if (mBound) {
1564                            disconnectService();
1565                        }
1566                        if (!connectToService()) {
1567                            Slog.e(TAG, "Failed to bind to media container service");
1568                            for (HandlerParams params : mPendingInstalls) {
1569                                // Indicate service bind error
1570                                params.serviceError();
1571                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1572                                        System.identityHashCode(params));
1573                            }
1574                            mPendingInstalls.clear();
1575                        }
1576                    }
1577                    break;
1578                }
1579                case MCS_UNBIND: {
1580                    // If there is no actual work left, then time to unbind.
1581                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1582
1583                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1584                        if (mBound) {
1585                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1586
1587                            disconnectService();
1588                        }
1589                    } else if (mPendingInstalls.size() > 0) {
1590                        // There are more pending requests in queue.
1591                        // Just post MCS_BOUND message to trigger processing
1592                        // of next pending install.
1593                        mHandler.sendEmptyMessage(MCS_BOUND);
1594                    }
1595
1596                    break;
1597                }
1598                case MCS_GIVE_UP: {
1599                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1600                    HandlerParams params = mPendingInstalls.remove(0);
1601                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1602                            System.identityHashCode(params));
1603                    break;
1604                }
1605                case SEND_PENDING_BROADCAST: {
1606                    String packages[];
1607                    ArrayList<String> components[];
1608                    int size = 0;
1609                    int uids[];
1610                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1611                    synchronized (mPackages) {
1612                        if (mPendingBroadcasts == null) {
1613                            return;
1614                        }
1615                        size = mPendingBroadcasts.size();
1616                        if (size <= 0) {
1617                            // Nothing to be done. Just return
1618                            return;
1619                        }
1620                        packages = new String[size];
1621                        components = new ArrayList[size];
1622                        uids = new int[size];
1623                        int i = 0;  // filling out the above arrays
1624
1625                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1626                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1627                            Iterator<Map.Entry<String, ArrayList<String>>> it
1628                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1629                                            .entrySet().iterator();
1630                            while (it.hasNext() && i < size) {
1631                                Map.Entry<String, ArrayList<String>> ent = it.next();
1632                                packages[i] = ent.getKey();
1633                                components[i] = ent.getValue();
1634                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1635                                uids[i] = (ps != null)
1636                                        ? UserHandle.getUid(packageUserId, ps.appId)
1637                                        : -1;
1638                                i++;
1639                            }
1640                        }
1641                        size = i;
1642                        mPendingBroadcasts.clear();
1643                    }
1644                    // Send broadcasts
1645                    for (int i = 0; i < size; i++) {
1646                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1647                    }
1648                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1649                    break;
1650                }
1651                case START_CLEANING_PACKAGE: {
1652                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1653                    final String packageName = (String)msg.obj;
1654                    final int userId = msg.arg1;
1655                    final boolean andCode = msg.arg2 != 0;
1656                    synchronized (mPackages) {
1657                        if (userId == UserHandle.USER_ALL) {
1658                            int[] users = sUserManager.getUserIds();
1659                            for (int user : users) {
1660                                mSettings.addPackageToCleanLPw(
1661                                        new PackageCleanItem(user, packageName, andCode));
1662                            }
1663                        } else {
1664                            mSettings.addPackageToCleanLPw(
1665                                    new PackageCleanItem(userId, packageName, andCode));
1666                        }
1667                    }
1668                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1669                    startCleaningPackages();
1670                } break;
1671                case POST_INSTALL: {
1672                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1673
1674                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1675                    final boolean didRestore = (msg.arg2 != 0);
1676                    mRunningInstalls.delete(msg.arg1);
1677
1678                    if (data != null) {
1679                        InstallArgs args = data.args;
1680                        PackageInstalledInfo parentRes = data.res;
1681
1682                        final boolean grantPermissions = (args.installFlags
1683                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1684                        final boolean killApp = (args.installFlags
1685                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1686                        final boolean virtualPreload = ((args.installFlags
1687                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1688                        final String[] grantedPermissions = args.installGrantPermissions;
1689
1690                        // Handle the parent package
1691                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1692                                virtualPreload, grantedPermissions, didRestore,
1693                                args.installerPackageName, args.observer);
1694
1695                        // Handle the child packages
1696                        final int childCount = (parentRes.addedChildPackages != null)
1697                                ? parentRes.addedChildPackages.size() : 0;
1698                        for (int i = 0; i < childCount; i++) {
1699                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1700                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1701                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1702                                    args.installerPackageName, args.observer);
1703                        }
1704
1705                        // Log tracing if needed
1706                        if (args.traceMethod != null) {
1707                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1708                                    args.traceCookie);
1709                        }
1710                    } else {
1711                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1712                    }
1713
1714                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1715                } break;
1716                case WRITE_SETTINGS: {
1717                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1718                    synchronized (mPackages) {
1719                        removeMessages(WRITE_SETTINGS);
1720                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1721                        mSettings.writeLPr();
1722                        mDirtyUsers.clear();
1723                    }
1724                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1725                } break;
1726                case WRITE_PACKAGE_RESTRICTIONS: {
1727                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1728                    synchronized (mPackages) {
1729                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1730                        for (int userId : mDirtyUsers) {
1731                            mSettings.writePackageRestrictionsLPr(userId);
1732                        }
1733                        mDirtyUsers.clear();
1734                    }
1735                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1736                } break;
1737                case WRITE_PACKAGE_LIST: {
1738                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1739                    synchronized (mPackages) {
1740                        removeMessages(WRITE_PACKAGE_LIST);
1741                        mSettings.writePackageListLPr(msg.arg1);
1742                    }
1743                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1744                } break;
1745                case CHECK_PENDING_VERIFICATION: {
1746                    final int verificationId = msg.arg1;
1747                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1748
1749                    if ((state != null) && !state.timeoutExtended()) {
1750                        final InstallArgs args = state.getInstallArgs();
1751                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1752
1753                        Slog.i(TAG, "Verification timed out for " + originUri);
1754                        mPendingVerification.remove(verificationId);
1755
1756                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1757
1758                        final UserHandle user = args.getUser();
1759                        if (getDefaultVerificationResponse(user)
1760                                == PackageManager.VERIFICATION_ALLOW) {
1761                            Slog.i(TAG, "Continuing with installation of " + originUri);
1762                            state.setVerifierResponse(Binder.getCallingUid(),
1763                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1764                            broadcastPackageVerified(verificationId, originUri,
1765                                    PackageManager.VERIFICATION_ALLOW, user);
1766                            try {
1767                                ret = args.copyApk(mContainerService, true);
1768                            } catch (RemoteException e) {
1769                                Slog.e(TAG, "Could not contact the ContainerService");
1770                            }
1771                        } else {
1772                            broadcastPackageVerified(verificationId, originUri,
1773                                    PackageManager.VERIFICATION_REJECT, user);
1774                        }
1775
1776                        Trace.asyncTraceEnd(
1777                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1778
1779                        processPendingInstall(args, ret);
1780                        mHandler.sendEmptyMessage(MCS_UNBIND);
1781                    }
1782                    break;
1783                }
1784                case PACKAGE_VERIFIED: {
1785                    final int verificationId = msg.arg1;
1786
1787                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1788                    if (state == null) {
1789                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1790                        break;
1791                    }
1792
1793                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1794
1795                    state.setVerifierResponse(response.callerUid, response.code);
1796
1797                    if (state.isVerificationComplete()) {
1798                        mPendingVerification.remove(verificationId);
1799
1800                        final InstallArgs args = state.getInstallArgs();
1801                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1802
1803                        int ret;
1804                        if (state.isInstallAllowed()) {
1805                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1806                            broadcastPackageVerified(verificationId, originUri,
1807                                    response.code, state.getInstallArgs().getUser());
1808                            try {
1809                                ret = args.copyApk(mContainerService, true);
1810                            } catch (RemoteException e) {
1811                                Slog.e(TAG, "Could not contact the ContainerService");
1812                            }
1813                        } else {
1814                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1815                        }
1816
1817                        Trace.asyncTraceEnd(
1818                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1819
1820                        processPendingInstall(args, ret);
1821                        mHandler.sendEmptyMessage(MCS_UNBIND);
1822                    }
1823
1824                    break;
1825                }
1826                case START_INTENT_FILTER_VERIFICATIONS: {
1827                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1828                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1829                            params.replacing, params.pkg);
1830                    break;
1831                }
1832                case INTENT_FILTER_VERIFIED: {
1833                    final int verificationId = msg.arg1;
1834
1835                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1836                            verificationId);
1837                    if (state == null) {
1838                        Slog.w(TAG, "Invalid IntentFilter verification token "
1839                                + verificationId + " received");
1840                        break;
1841                    }
1842
1843                    final int userId = state.getUserId();
1844
1845                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1846                            "Processing IntentFilter verification with token:"
1847                            + verificationId + " and userId:" + userId);
1848
1849                    final IntentFilterVerificationResponse response =
1850                            (IntentFilterVerificationResponse) msg.obj;
1851
1852                    state.setVerifierResponse(response.callerUid, response.code);
1853
1854                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1855                            "IntentFilter verification with token:" + verificationId
1856                            + " and userId:" + userId
1857                            + " is settings verifier response with response code:"
1858                            + response.code);
1859
1860                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1861                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1862                                + response.getFailedDomainsString());
1863                    }
1864
1865                    if (state.isVerificationComplete()) {
1866                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1867                    } else {
1868                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1869                                "IntentFilter verification with token:" + verificationId
1870                                + " was not said to be complete");
1871                    }
1872
1873                    break;
1874                }
1875                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1876                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1877                            mInstantAppResolverConnection,
1878                            (InstantAppRequest) msg.obj,
1879                            mInstantAppInstallerActivity,
1880                            mHandler);
1881                }
1882            }
1883        }
1884    }
1885
1886    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1887        @Override
1888        public void onGidsChanged(int appId, int userId) {
1889            mHandler.post(new Runnable() {
1890                @Override
1891                public void run() {
1892                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1893                }
1894            });
1895        }
1896        @Override
1897        public void onPermissionGranted(int uid, int userId) {
1898            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1899
1900            // Not critical; if this is lost, the application has to request again.
1901            synchronized (mPackages) {
1902                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1903            }
1904        }
1905        @Override
1906        public void onInstallPermissionGranted() {
1907            synchronized (mPackages) {
1908                scheduleWriteSettingsLocked();
1909            }
1910        }
1911        @Override
1912        public void onPermissionRevoked(int uid, int userId) {
1913            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1914
1915            synchronized (mPackages) {
1916                // Critical; after this call the application should never have the permission
1917                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1918            }
1919
1920            final int appId = UserHandle.getAppId(uid);
1921            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1922        }
1923        @Override
1924        public void onInstallPermissionRevoked() {
1925            synchronized (mPackages) {
1926                scheduleWriteSettingsLocked();
1927            }
1928        }
1929        @Override
1930        public void onPermissionUpdated(int userId) {
1931            synchronized (mPackages) {
1932                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1933            }
1934        }
1935        @Override
1936        public void onInstallPermissionUpdated() {
1937            synchronized (mPackages) {
1938                scheduleWriteSettingsLocked();
1939            }
1940        }
1941        @Override
1942        public void onPermissionRemoved() {
1943            synchronized (mPackages) {
1944                mSettings.writeLPr();
1945            }
1946        }
1947    };
1948
1949    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1950            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1951            boolean launchedForRestore, String installerPackage,
1952            IPackageInstallObserver2 installObserver) {
1953        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1954            // Send the removed broadcasts
1955            if (res.removedInfo != null) {
1956                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1957            }
1958
1959            // Now that we successfully installed the package, grant runtime
1960            // permissions if requested before broadcasting the install. Also
1961            // for legacy apps in permission review mode we clear the permission
1962            // review flag which is used to emulate runtime permissions for
1963            // legacy apps.
1964            if (grantPermissions) {
1965                final int callingUid = Binder.getCallingUid();
1966                mPermissionManager.grantRequestedRuntimePermissions(
1967                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1968                        mPermissionCallback);
1969            }
1970
1971            final boolean update = res.removedInfo != null
1972                    && res.removedInfo.removedPackage != null;
1973            final String installerPackageName =
1974                    res.installerPackageName != null
1975                            ? res.installerPackageName
1976                            : res.removedInfo != null
1977                                    ? res.removedInfo.installerPackageName
1978                                    : null;
1979
1980            // If this is the first time we have child packages for a disabled privileged
1981            // app that had no children, we grant requested runtime permissions to the new
1982            // children if the parent on the system image had them already granted.
1983            if (res.pkg.parentPackage != null) {
1984                final int callingUid = Binder.getCallingUid();
1985                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1986                        res.pkg, callingUid, mPermissionCallback);
1987            }
1988
1989            synchronized (mPackages) {
1990                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1991            }
1992
1993            final String packageName = res.pkg.applicationInfo.packageName;
1994
1995            // Determine the set of users who are adding this package for
1996            // the first time vs. those who are seeing an update.
1997            int[] firstUsers = EMPTY_INT_ARRAY;
1998            int[] updateUsers = EMPTY_INT_ARRAY;
1999            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
2000            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
2001            for (int newUser : res.newUsers) {
2002                if (ps.getInstantApp(newUser)) {
2003                    continue;
2004                }
2005                if (allNewUsers) {
2006                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
2007                    continue;
2008                }
2009                boolean isNew = true;
2010                for (int origUser : res.origUsers) {
2011                    if (origUser == newUser) {
2012                        isNew = false;
2013                        break;
2014                    }
2015                }
2016                if (isNew) {
2017                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
2018                } else {
2019                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
2020                }
2021            }
2022
2023            // Send installed broadcasts if the package is not a static shared lib.
2024            if (res.pkg.staticSharedLibName == null) {
2025                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2026
2027                // Send added for users that see the package for the first time
2028                // sendPackageAddedForNewUsers also deals with system apps
2029                int appId = UserHandle.getAppId(res.uid);
2030                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2031                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2032                        virtualPreload /*startReceiver*/, appId, firstUsers);
2033
2034                // Send added for users that don't see the package for the first time
2035                Bundle extras = new Bundle(1);
2036                extras.putInt(Intent.EXTRA_UID, res.uid);
2037                if (update) {
2038                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2039                }
2040                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2041                        extras, 0 /*flags*/,
2042                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
2043                if (installerPackageName != null) {
2044                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2045                            extras, 0 /*flags*/,
2046                            installerPackageName, null /*finishedReceiver*/, updateUsers);
2047                }
2048
2049                // Send replaced for users that don't see the package for the first time
2050                if (update) {
2051                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2052                            packageName, extras, 0 /*flags*/,
2053                            null /*targetPackage*/, null /*finishedReceiver*/,
2054                            updateUsers);
2055                    if (installerPackageName != null) {
2056                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2057                                extras, 0 /*flags*/,
2058                                installerPackageName, null /*finishedReceiver*/, updateUsers);
2059                    }
2060                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2061                            null /*package*/, null /*extras*/, 0 /*flags*/,
2062                            packageName /*targetPackage*/,
2063                            null /*finishedReceiver*/, updateUsers);
2064                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2065                    // First-install and we did a restore, so we're responsible for the
2066                    // first-launch broadcast.
2067                    if (DEBUG_BACKUP) {
2068                        Slog.i(TAG, "Post-restore of " + packageName
2069                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2070                    }
2071                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2072                }
2073
2074                // Send broadcast package appeared if forward locked/external for all users
2075                // treat asec-hosted packages like removable media on upgrade
2076                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2077                    if (DEBUG_INSTALL) {
2078                        Slog.i(TAG, "upgrading pkg " + res.pkg
2079                                + " is ASEC-hosted -> AVAILABLE");
2080                    }
2081                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2082                    ArrayList<String> pkgList = new ArrayList<>(1);
2083                    pkgList.add(packageName);
2084                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2085                }
2086            }
2087
2088            // Work that needs to happen on first install within each user
2089            if (firstUsers != null && firstUsers.length > 0) {
2090                synchronized (mPackages) {
2091                    for (int userId : firstUsers) {
2092                        // If this app is a browser and it's newly-installed for some
2093                        // users, clear any default-browser state in those users. The
2094                        // app's nature doesn't depend on the user, so we can just check
2095                        // its browser nature in any user and generalize.
2096                        if (packageIsBrowser(packageName, userId)) {
2097                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2098                        }
2099
2100                        // We may also need to apply pending (restored) runtime
2101                        // permission grants within these users.
2102                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2103                    }
2104                }
2105            }
2106
2107            // Log current value of "unknown sources" setting
2108            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2109                    getUnknownSourcesSettings());
2110
2111            // Remove the replaced package's older resources safely now
2112            // We delete after a gc for applications  on sdcard.
2113            if (res.removedInfo != null && res.removedInfo.args != null) {
2114                Runtime.getRuntime().gc();
2115                synchronized (mInstallLock) {
2116                    res.removedInfo.args.doPostDeleteLI(true);
2117                }
2118            } else {
2119                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2120                // and not block here.
2121                VMRuntime.getRuntime().requestConcurrentGC();
2122            }
2123
2124            // Notify DexManager that the package was installed for new users.
2125            // The updated users should already be indexed and the package code paths
2126            // should not change.
2127            // Don't notify the manager for ephemeral apps as they are not expected to
2128            // survive long enough to benefit of background optimizations.
2129            for (int userId : firstUsers) {
2130                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2131                // There's a race currently where some install events may interleave with an uninstall.
2132                // This can lead to package info being null (b/36642664).
2133                if (info != null) {
2134                    mDexManager.notifyPackageInstalled(info, userId);
2135                }
2136            }
2137        }
2138
2139        // If someone is watching installs - notify them
2140        if (installObserver != null) {
2141            try {
2142                Bundle extras = extrasForInstallResult(res);
2143                installObserver.onPackageInstalled(res.name, res.returnCode,
2144                        res.returnMsg, extras);
2145            } catch (RemoteException e) {
2146                Slog.i(TAG, "Observer no longer exists.");
2147            }
2148        }
2149    }
2150
2151    private StorageEventListener mStorageListener = new StorageEventListener() {
2152        @Override
2153        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2154            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2155                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2156                    final String volumeUuid = vol.getFsUuid();
2157
2158                    // Clean up any users or apps that were removed or recreated
2159                    // while this volume was missing
2160                    sUserManager.reconcileUsers(volumeUuid);
2161                    reconcileApps(volumeUuid);
2162
2163                    // Clean up any install sessions that expired or were
2164                    // cancelled while this volume was missing
2165                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2166
2167                    loadPrivatePackages(vol);
2168
2169                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2170                    unloadPrivatePackages(vol);
2171                }
2172            }
2173        }
2174
2175        @Override
2176        public void onVolumeForgotten(String fsUuid) {
2177            if (TextUtils.isEmpty(fsUuid)) {
2178                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2179                return;
2180            }
2181
2182            // Remove any apps installed on the forgotten volume
2183            synchronized (mPackages) {
2184                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2185                for (PackageSetting ps : packages) {
2186                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2187                    deletePackageVersioned(new VersionedPackage(ps.name,
2188                            PackageManager.VERSION_CODE_HIGHEST),
2189                            new LegacyPackageDeleteObserver(null).getBinder(),
2190                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2191                    // Try very hard to release any references to this package
2192                    // so we don't risk the system server being killed due to
2193                    // open FDs
2194                    AttributeCache.instance().removePackage(ps.name);
2195                }
2196
2197                mSettings.onVolumeForgotten(fsUuid);
2198                mSettings.writeLPr();
2199            }
2200        }
2201    };
2202
2203    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2204        Bundle extras = null;
2205        switch (res.returnCode) {
2206            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2207                extras = new Bundle();
2208                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2209                        res.origPermission);
2210                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2211                        res.origPackage);
2212                break;
2213            }
2214            case PackageManager.INSTALL_SUCCEEDED: {
2215                extras = new Bundle();
2216                extras.putBoolean(Intent.EXTRA_REPLACING,
2217                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2218                break;
2219            }
2220        }
2221        return extras;
2222    }
2223
2224    void scheduleWriteSettingsLocked() {
2225        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2226            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2227        }
2228    }
2229
2230    void scheduleWritePackageListLocked(int userId) {
2231        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2232            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2233            msg.arg1 = userId;
2234            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2235        }
2236    }
2237
2238    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2239        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2240        scheduleWritePackageRestrictionsLocked(userId);
2241    }
2242
2243    void scheduleWritePackageRestrictionsLocked(int userId) {
2244        final int[] userIds = (userId == UserHandle.USER_ALL)
2245                ? sUserManager.getUserIds() : new int[]{userId};
2246        for (int nextUserId : userIds) {
2247            if (!sUserManager.exists(nextUserId)) return;
2248            mDirtyUsers.add(nextUserId);
2249            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2250                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2251            }
2252        }
2253    }
2254
2255    public static PackageManagerService main(Context context, Installer installer,
2256            boolean factoryTest, boolean onlyCore) {
2257        // Self-check for initial settings.
2258        PackageManagerServiceCompilerMapping.checkProperties();
2259
2260        PackageManagerService m = new PackageManagerService(context, installer,
2261                factoryTest, onlyCore);
2262        m.enableSystemUserPackages();
2263        ServiceManager.addService("package", m);
2264        final PackageManagerNative pmn = m.new PackageManagerNative();
2265        ServiceManager.addService("package_native", pmn);
2266        return m;
2267    }
2268
2269    private void enableSystemUserPackages() {
2270        if (!UserManager.isSplitSystemUser()) {
2271            return;
2272        }
2273        // For system user, enable apps based on the following conditions:
2274        // - app is whitelisted or belong to one of these groups:
2275        //   -- system app which has no launcher icons
2276        //   -- system app which has INTERACT_ACROSS_USERS permission
2277        //   -- system IME app
2278        // - app is not in the blacklist
2279        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2280        Set<String> enableApps = new ArraySet<>();
2281        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2282                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2283                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2284        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2285        enableApps.addAll(wlApps);
2286        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2287                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2288        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2289        enableApps.removeAll(blApps);
2290        Log.i(TAG, "Applications installed for system user: " + enableApps);
2291        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2292                UserHandle.SYSTEM);
2293        final int allAppsSize = allAps.size();
2294        synchronized (mPackages) {
2295            for (int i = 0; i < allAppsSize; i++) {
2296                String pName = allAps.get(i);
2297                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2298                // Should not happen, but we shouldn't be failing if it does
2299                if (pkgSetting == null) {
2300                    continue;
2301                }
2302                boolean install = enableApps.contains(pName);
2303                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2304                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2305                            + " for system user");
2306                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2307                }
2308            }
2309            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2310        }
2311    }
2312
2313    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2314        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2315                Context.DISPLAY_SERVICE);
2316        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2317    }
2318
2319    /**
2320     * Requests that files preopted on a secondary system partition be copied to the data partition
2321     * if possible.  Note that the actual copying of the files is accomplished by init for security
2322     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2323     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2324     */
2325    private static void requestCopyPreoptedFiles() {
2326        final int WAIT_TIME_MS = 100;
2327        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2328        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2329            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2330            // We will wait for up to 100 seconds.
2331            final long timeStart = SystemClock.uptimeMillis();
2332            final long timeEnd = timeStart + 100 * 1000;
2333            long timeNow = timeStart;
2334            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2335                try {
2336                    Thread.sleep(WAIT_TIME_MS);
2337                } catch (InterruptedException e) {
2338                    // Do nothing
2339                }
2340                timeNow = SystemClock.uptimeMillis();
2341                if (timeNow > timeEnd) {
2342                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2343                    Slog.wtf(TAG, "cppreopt did not finish!");
2344                    break;
2345                }
2346            }
2347
2348            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2349        }
2350    }
2351
2352    public PackageManagerService(Context context, Installer installer,
2353            boolean factoryTest, boolean onlyCore) {
2354        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2355        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2356        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2357                SystemClock.uptimeMillis());
2358
2359        if (mSdkVersion <= 0) {
2360            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2361        }
2362
2363        mContext = context;
2364
2365        mPermissionReviewRequired = context.getResources().getBoolean(
2366                R.bool.config_permissionReviewRequired);
2367
2368        mFactoryTest = factoryTest;
2369        mOnlyCore = onlyCore;
2370        mMetrics = new DisplayMetrics();
2371        mInstaller = installer;
2372
2373        // Create sub-components that provide services / data. Order here is important.
2374        synchronized (mInstallLock) {
2375        synchronized (mPackages) {
2376            // Expose private service for system components to use.
2377            LocalServices.addService(
2378                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2379            sUserManager = new UserManagerService(context, this,
2380                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2381            mPermissionManager = PermissionManagerService.create(context,
2382                    new DefaultPermissionGrantedCallback() {
2383                        @Override
2384                        public void onDefaultRuntimePermissionsGranted(int userId) {
2385                            synchronized(mPackages) {
2386                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2387                            }
2388                        }
2389                    }, mPackages /*externalLock*/);
2390            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2391            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2392        }
2393        }
2394        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2395                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2396        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2397                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2398        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2399                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2400        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2401                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2402        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2403                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2404        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2405                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2406
2407        String separateProcesses = SystemProperties.get("debug.separate_processes");
2408        if (separateProcesses != null && separateProcesses.length() > 0) {
2409            if ("*".equals(separateProcesses)) {
2410                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2411                mSeparateProcesses = null;
2412                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2413            } else {
2414                mDefParseFlags = 0;
2415                mSeparateProcesses = separateProcesses.split(",");
2416                Slog.w(TAG, "Running with debug.separate_processes: "
2417                        + separateProcesses);
2418            }
2419        } else {
2420            mDefParseFlags = 0;
2421            mSeparateProcesses = null;
2422        }
2423
2424        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2425                "*dexopt*");
2426        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2427        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2428
2429        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2430                FgThread.get().getLooper());
2431
2432        getDefaultDisplayMetrics(context, mMetrics);
2433
2434        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2435        SystemConfig systemConfig = SystemConfig.getInstance();
2436        mGlobalGids = systemConfig.getGlobalGids();
2437        mSystemPermissions = systemConfig.getSystemPermissions();
2438        mAvailableFeatures = systemConfig.getAvailableFeatures();
2439        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2440
2441        mProtectedPackages = new ProtectedPackages(mContext);
2442
2443        synchronized (mInstallLock) {
2444        // writer
2445        synchronized (mPackages) {
2446            mHandlerThread = new ServiceThread(TAG,
2447                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2448            mHandlerThread.start();
2449            mHandler = new PackageHandler(mHandlerThread.getLooper());
2450            mProcessLoggingHandler = new ProcessLoggingHandler();
2451            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2452            mInstantAppRegistry = new InstantAppRegistry(this);
2453
2454            File dataDir = Environment.getDataDirectory();
2455            mAppInstallDir = new File(dataDir, "app");
2456            mAppLib32InstallDir = new File(dataDir, "app-lib");
2457            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2458
2459            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2460            final int builtInLibCount = libConfig.size();
2461            for (int i = 0; i < builtInLibCount; i++) {
2462                String name = libConfig.keyAt(i);
2463                String path = libConfig.valueAt(i);
2464                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2465                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2466            }
2467
2468            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2469
2470            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2471            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2472            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2473
2474            // Clean up orphaned packages for which the code path doesn't exist
2475            // and they are an update to a system app - caused by bug/32321269
2476            final int packageSettingCount = mSettings.mPackages.size();
2477            for (int i = packageSettingCount - 1; i >= 0; i--) {
2478                PackageSetting ps = mSettings.mPackages.valueAt(i);
2479                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2480                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2481                    mSettings.mPackages.removeAt(i);
2482                    mSettings.enableSystemPackageLPw(ps.name);
2483                }
2484            }
2485
2486            if (mFirstBoot) {
2487                requestCopyPreoptedFiles();
2488            }
2489
2490            String customResolverActivity = Resources.getSystem().getString(
2491                    R.string.config_customResolverActivity);
2492            if (TextUtils.isEmpty(customResolverActivity)) {
2493                customResolverActivity = null;
2494            } else {
2495                mCustomResolverComponentName = ComponentName.unflattenFromString(
2496                        customResolverActivity);
2497            }
2498
2499            long startTime = SystemClock.uptimeMillis();
2500
2501            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2502                    startTime);
2503
2504            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2505            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2506
2507            if (bootClassPath == null) {
2508                Slog.w(TAG, "No BOOTCLASSPATH found!");
2509            }
2510
2511            if (systemServerClassPath == null) {
2512                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2513            }
2514
2515            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2516
2517            final VersionInfo ver = mSettings.getInternalVersion();
2518            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2519            if (mIsUpgrade) {
2520                logCriticalInfo(Log.INFO,
2521                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2522            }
2523
2524            // when upgrading from pre-M, promote system app permissions from install to runtime
2525            mPromoteSystemApps =
2526                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2527
2528            // When upgrading from pre-N, we need to handle package extraction like first boot,
2529            // as there is no profiling data available.
2530            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2531
2532            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2533
2534            // save off the names of pre-existing system packages prior to scanning; we don't
2535            // want to automatically grant runtime permissions for new system apps
2536            if (mPromoteSystemApps) {
2537                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2538                while (pkgSettingIter.hasNext()) {
2539                    PackageSetting ps = pkgSettingIter.next();
2540                    if (isSystemApp(ps)) {
2541                        mExistingSystemPackages.add(ps.name);
2542                    }
2543                }
2544            }
2545
2546            mCacheDir = preparePackageParserCache(mIsUpgrade);
2547
2548            // Set flag to monitor and not change apk file paths when
2549            // scanning install directories.
2550            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2551
2552            if (mIsUpgrade || mFirstBoot) {
2553                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2554            }
2555
2556            // Collect vendor overlay packages. (Do this before scanning any apps.)
2557            // For security and version matching reason, only consider
2558            // overlay packages if they reside in the right directory.
2559            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2560                    | PackageParser.PARSE_IS_SYSTEM
2561                    | PackageParser.PARSE_IS_SYSTEM_DIR
2562                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2563
2564            mParallelPackageParserCallback.findStaticOverlayPackages();
2565
2566            // Find base frameworks (resource packages without code).
2567            scanDirTracedLI(frameworkDir, mDefParseFlags
2568                    | PackageParser.PARSE_IS_SYSTEM
2569                    | PackageParser.PARSE_IS_SYSTEM_DIR
2570                    | PackageParser.PARSE_IS_PRIVILEGED,
2571                    scanFlags | SCAN_NO_DEX, 0);
2572
2573            // Collected privileged system packages.
2574            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2575            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2576                    | PackageParser.PARSE_IS_SYSTEM
2577                    | PackageParser.PARSE_IS_SYSTEM_DIR
2578                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2579
2580            // Collect ordinary system packages.
2581            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2582            scanDirTracedLI(systemAppDir, mDefParseFlags
2583                    | PackageParser.PARSE_IS_SYSTEM
2584                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2585
2586            // Collect all vendor packages.
2587            File vendorAppDir = new File("/vendor/app");
2588            try {
2589                vendorAppDir = vendorAppDir.getCanonicalFile();
2590            } catch (IOException e) {
2591                // failed to look up canonical path, continue with original one
2592            }
2593            scanDirTracedLI(vendorAppDir, mDefParseFlags
2594                    | PackageParser.PARSE_IS_SYSTEM
2595                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2596
2597            // Collect all OEM packages.
2598            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2599            scanDirTracedLI(oemAppDir, mDefParseFlags
2600                    | PackageParser.PARSE_IS_SYSTEM
2601                    | PackageParser.PARSE_IS_SYSTEM_DIR
2602                    | PackageParser.PARSE_IS_OEM, scanFlags, 0);
2603
2604            // Prune any system packages that no longer exist.
2605            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2606            // Stub packages must either be replaced with full versions in the /data
2607            // partition or be disabled.
2608            final List<String> stubSystemApps = new ArrayList<>();
2609            if (!mOnlyCore) {
2610                // do this first before mucking with mPackages for the "expecting better" case
2611                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2612                while (pkgIterator.hasNext()) {
2613                    final PackageParser.Package pkg = pkgIterator.next();
2614                    if (pkg.isStub) {
2615                        stubSystemApps.add(pkg.packageName);
2616                    }
2617                }
2618
2619                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2620                while (psit.hasNext()) {
2621                    PackageSetting ps = psit.next();
2622
2623                    /*
2624                     * If this is not a system app, it can't be a
2625                     * disable system app.
2626                     */
2627                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2628                        continue;
2629                    }
2630
2631                    /*
2632                     * If the package is scanned, it's not erased.
2633                     */
2634                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2635                    if (scannedPkg != null) {
2636                        /*
2637                         * If the system app is both scanned and in the
2638                         * disabled packages list, then it must have been
2639                         * added via OTA. Remove it from the currently
2640                         * scanned package so the previously user-installed
2641                         * application can be scanned.
2642                         */
2643                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2644                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2645                                    + ps.name + "; removing system app.  Last known codePath="
2646                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2647                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2648                                    + scannedPkg.mVersionCode);
2649                            removePackageLI(scannedPkg, true);
2650                            mExpectingBetter.put(ps.name, ps.codePath);
2651                        }
2652
2653                        continue;
2654                    }
2655
2656                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2657                        psit.remove();
2658                        logCriticalInfo(Log.WARN, "System package " + ps.name
2659                                + " no longer exists; it's data will be wiped");
2660                        // Actual deletion of code and data will be handled by later
2661                        // reconciliation step
2662                    } else {
2663                        // we still have a disabled system package, but, it still might have
2664                        // been removed. check the code path still exists and check there's
2665                        // still a package. the latter can happen if an OTA keeps the same
2666                        // code path, but, changes the package name.
2667                        final PackageSetting disabledPs =
2668                                mSettings.getDisabledSystemPkgLPr(ps.name);
2669                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2670                                || disabledPs.pkg == null) {
2671                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2672                        }
2673                    }
2674                }
2675            }
2676
2677            //look for any incomplete package installations
2678            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2679            for (int i = 0; i < deletePkgsList.size(); i++) {
2680                // Actual deletion of code and data will be handled by later
2681                // reconciliation step
2682                final String packageName = deletePkgsList.get(i).name;
2683                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2684                synchronized (mPackages) {
2685                    mSettings.removePackageLPw(packageName);
2686                }
2687            }
2688
2689            //delete tmp files
2690            deleteTempPackageFiles();
2691
2692            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2693
2694            // Remove any shared userIDs that have no associated packages
2695            mSettings.pruneSharedUsersLPw();
2696            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2697            final int systemPackagesCount = mPackages.size();
2698            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2699                    + " ms, packageCount: " + systemPackagesCount
2700                    + " , timePerPackage: "
2701                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2702                    + " , cached: " + cachedSystemApps);
2703            if (mIsUpgrade && systemPackagesCount > 0) {
2704                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2705                        ((int) systemScanTime) / systemPackagesCount);
2706            }
2707            if (!mOnlyCore) {
2708                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2709                        SystemClock.uptimeMillis());
2710                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2711
2712                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2713                        | PackageParser.PARSE_FORWARD_LOCK,
2714                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2715
2716                // Remove disable package settings for updated system apps that were
2717                // removed via an OTA. If the update is no longer present, remove the
2718                // app completely. Otherwise, revoke their system privileges.
2719                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2720                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2721                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2722
2723                    final String msg;
2724                    if (deletedPkg == null) {
2725                        // should have found an update, but, we didn't; remove everything
2726                        msg = "Updated system package " + deletedAppName
2727                                + " no longer exists; removing its data";
2728                        // Actual deletion of code and data will be handled by later
2729                        // reconciliation step
2730                    } else {
2731                        // found an update; revoke system privileges
2732                        msg = "Updated system package + " + deletedAppName
2733                                + " no longer exists; revoking system privileges";
2734
2735                        // Don't do anything if a stub is removed from the system image. If
2736                        // we were to remove the uncompressed version from the /data partition,
2737                        // this is where it'd be done.
2738
2739                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2740                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2741                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2742                    }
2743                    logCriticalInfo(Log.WARN, msg);
2744                }
2745
2746                /*
2747                 * Make sure all system apps that we expected to appear on
2748                 * the userdata partition actually showed up. If they never
2749                 * appeared, crawl back and revive the system version.
2750                 */
2751                for (int i = 0; i < mExpectingBetter.size(); i++) {
2752                    final String packageName = mExpectingBetter.keyAt(i);
2753                    if (!mPackages.containsKey(packageName)) {
2754                        final File scanFile = mExpectingBetter.valueAt(i);
2755
2756                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2757                                + " but never showed up; reverting to system");
2758
2759                        int reparseFlags = mDefParseFlags;
2760                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2761                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2762                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2763                                    | PackageParser.PARSE_IS_PRIVILEGED;
2764                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2765                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2766                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2767                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2768                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2769                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2770                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2771                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2772                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2773                                    | PackageParser.PARSE_IS_OEM;
2774                        } else {
2775                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2776                            continue;
2777                        }
2778
2779                        mSettings.enableSystemPackageLPw(packageName);
2780
2781                        try {
2782                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2783                        } catch (PackageManagerException e) {
2784                            Slog.e(TAG, "Failed to parse original system package: "
2785                                    + e.getMessage());
2786                        }
2787                    }
2788                }
2789
2790                // Uncompress and install any stubbed system applications.
2791                // This must be done last to ensure all stubs are replaced or disabled.
2792                decompressSystemApplications(stubSystemApps, scanFlags);
2793
2794                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2795                                - cachedSystemApps;
2796
2797                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2798                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2799                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2800                        + " ms, packageCount: " + dataPackagesCount
2801                        + " , timePerPackage: "
2802                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2803                        + " , cached: " + cachedNonSystemApps);
2804                if (mIsUpgrade && dataPackagesCount > 0) {
2805                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2806                            ((int) dataScanTime) / dataPackagesCount);
2807                }
2808            }
2809            mExpectingBetter.clear();
2810
2811            // Resolve the storage manager.
2812            mStorageManagerPackage = getStorageManagerPackageName();
2813
2814            // Resolve protected action filters. Only the setup wizard is allowed to
2815            // have a high priority filter for these actions.
2816            mSetupWizardPackage = getSetupWizardPackageName();
2817            if (mProtectedFilters.size() > 0) {
2818                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2819                    Slog.i(TAG, "No setup wizard;"
2820                        + " All protected intents capped to priority 0");
2821                }
2822                for (ActivityIntentInfo filter : mProtectedFilters) {
2823                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2824                        if (DEBUG_FILTERS) {
2825                            Slog.i(TAG, "Found setup wizard;"
2826                                + " allow priority " + filter.getPriority() + ";"
2827                                + " package: " + filter.activity.info.packageName
2828                                + " activity: " + filter.activity.className
2829                                + " priority: " + filter.getPriority());
2830                        }
2831                        // skip setup wizard; allow it to keep the high priority filter
2832                        continue;
2833                    }
2834                    if (DEBUG_FILTERS) {
2835                        Slog.i(TAG, "Protected action; cap priority to 0;"
2836                                + " package: " + filter.activity.info.packageName
2837                                + " activity: " + filter.activity.className
2838                                + " origPrio: " + filter.getPriority());
2839                    }
2840                    filter.setPriority(0);
2841                }
2842            }
2843            mDeferProtectedFilters = false;
2844            mProtectedFilters.clear();
2845
2846            // Now that we know all of the shared libraries, update all clients to have
2847            // the correct library paths.
2848            updateAllSharedLibrariesLPw(null);
2849
2850            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2851                // NOTE: We ignore potential failures here during a system scan (like
2852                // the rest of the commands above) because there's precious little we
2853                // can do about it. A settings error is reported, though.
2854                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2855            }
2856
2857            // Now that we know all the packages we are keeping,
2858            // read and update their last usage times.
2859            mPackageUsage.read(mPackages);
2860            mCompilerStats.read();
2861
2862            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2863                    SystemClock.uptimeMillis());
2864            Slog.i(TAG, "Time to scan packages: "
2865                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2866                    + " seconds");
2867
2868            // If the platform SDK has changed since the last time we booted,
2869            // we need to re-grant app permission to catch any new ones that
2870            // appear.  This is really a hack, and means that apps can in some
2871            // cases get permissions that the user didn't initially explicitly
2872            // allow...  it would be nice to have some better way to handle
2873            // this situation.
2874            int updateFlags = UPDATE_PERMISSIONS_ALL;
2875            if (ver.sdkVersion != mSdkVersion) {
2876                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2877                        + mSdkVersion + "; regranting permissions for internal storage");
2878                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2879            }
2880            updatePermissionsLocked(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2881            ver.sdkVersion = mSdkVersion;
2882
2883            // If this is the first boot or an update from pre-M, and it is a normal
2884            // boot, then we need to initialize the default preferred apps across
2885            // all defined users.
2886            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2887                for (UserInfo user : sUserManager.getUsers(true)) {
2888                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2889                    applyFactoryDefaultBrowserLPw(user.id);
2890                    primeDomainVerificationsLPw(user.id);
2891                }
2892            }
2893
2894            // Prepare storage for system user really early during boot,
2895            // since core system apps like SettingsProvider and SystemUI
2896            // can't wait for user to start
2897            final int storageFlags;
2898            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2899                storageFlags = StorageManager.FLAG_STORAGE_DE;
2900            } else {
2901                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2902            }
2903            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2904                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2905                    true /* onlyCoreApps */);
2906            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2907                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
2908                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2909                traceLog.traceBegin("AppDataFixup");
2910                try {
2911                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2912                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2913                } catch (InstallerException e) {
2914                    Slog.w(TAG, "Trouble fixing GIDs", e);
2915                }
2916                traceLog.traceEnd();
2917
2918                traceLog.traceBegin("AppDataPrepare");
2919                if (deferPackages == null || deferPackages.isEmpty()) {
2920                    return;
2921                }
2922                int count = 0;
2923                for (String pkgName : deferPackages) {
2924                    PackageParser.Package pkg = null;
2925                    synchronized (mPackages) {
2926                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2927                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2928                            pkg = ps.pkg;
2929                        }
2930                    }
2931                    if (pkg != null) {
2932                        synchronized (mInstallLock) {
2933                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2934                                    true /* maybeMigrateAppData */);
2935                        }
2936                        count++;
2937                    }
2938                }
2939                traceLog.traceEnd();
2940                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2941            }, "prepareAppData");
2942
2943            // If this is first boot after an OTA, and a normal boot, then
2944            // we need to clear code cache directories.
2945            // Note that we do *not* clear the application profiles. These remain valid
2946            // across OTAs and are used to drive profile verification (post OTA) and
2947            // profile compilation (without waiting to collect a fresh set of profiles).
2948            if (mIsUpgrade && !onlyCore) {
2949                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2950                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2951                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2952                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2953                        // No apps are running this early, so no need to freeze
2954                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2955                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2956                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2957                    }
2958                }
2959                ver.fingerprint = Build.FINGERPRINT;
2960            }
2961
2962            checkDefaultBrowser();
2963
2964            // clear only after permissions and other defaults have been updated
2965            mExistingSystemPackages.clear();
2966            mPromoteSystemApps = false;
2967
2968            // All the changes are done during package scanning.
2969            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2970
2971            // can downgrade to reader
2972            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2973            mSettings.writeLPr();
2974            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2975            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2976                    SystemClock.uptimeMillis());
2977
2978            if (!mOnlyCore) {
2979                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2980                mRequiredInstallerPackage = getRequiredInstallerLPr();
2981                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2982                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2983                if (mIntentFilterVerifierComponent != null) {
2984                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2985                            mIntentFilterVerifierComponent);
2986                } else {
2987                    mIntentFilterVerifier = null;
2988                }
2989                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2990                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2991                        SharedLibraryInfo.VERSION_UNDEFINED);
2992                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2993                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2994                        SharedLibraryInfo.VERSION_UNDEFINED);
2995            } else {
2996                mRequiredVerifierPackage = null;
2997                mRequiredInstallerPackage = null;
2998                mRequiredUninstallerPackage = null;
2999                mIntentFilterVerifierComponent = null;
3000                mIntentFilterVerifier = null;
3001                mServicesSystemSharedLibraryPackageName = null;
3002                mSharedSystemSharedLibraryPackageName = null;
3003            }
3004
3005            mInstallerService = new PackageInstallerService(context, this);
3006            final Pair<ComponentName, String> instantAppResolverComponent =
3007                    getInstantAppResolverLPr();
3008            if (instantAppResolverComponent != null) {
3009                if (DEBUG_EPHEMERAL) {
3010                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3011                }
3012                mInstantAppResolverConnection = new EphemeralResolverConnection(
3013                        mContext, instantAppResolverComponent.first,
3014                        instantAppResolverComponent.second);
3015                mInstantAppResolverSettingsComponent =
3016                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3017            } else {
3018                mInstantAppResolverConnection = null;
3019                mInstantAppResolverSettingsComponent = null;
3020            }
3021            updateInstantAppInstallerLocked(null);
3022
3023            // Read and update the usage of dex files.
3024            // Do this at the end of PM init so that all the packages have their
3025            // data directory reconciled.
3026            // At this point we know the code paths of the packages, so we can validate
3027            // the disk file and build the internal cache.
3028            // The usage file is expected to be small so loading and verifying it
3029            // should take a fairly small time compare to the other activities (e.g. package
3030            // scanning).
3031            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3032            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3033            for (int userId : currentUserIds) {
3034                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3035            }
3036            mDexManager.load(userPackages);
3037            if (mIsUpgrade) {
3038                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3039                        (int) (SystemClock.uptimeMillis() - startTime));
3040            }
3041        } // synchronized (mPackages)
3042        } // synchronized (mInstallLock)
3043
3044        // Now after opening every single application zip, make sure they
3045        // are all flushed.  Not really needed, but keeps things nice and
3046        // tidy.
3047        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3048        Runtime.getRuntime().gc();
3049        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3050
3051        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3052        FallbackCategoryProvider.loadFallbacks();
3053        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3054
3055        // The initial scanning above does many calls into installd while
3056        // holding the mPackages lock, but we're mostly interested in yelling
3057        // once we have a booted system.
3058        mInstaller.setWarnIfHeld(mPackages);
3059
3060        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3061    }
3062
3063    /**
3064     * Uncompress and install stub applications.
3065     * <p>In order to save space on the system partition, some applications are shipped in a
3066     * compressed form. In addition the compressed bits for the full application, the
3067     * system image contains a tiny stub comprised of only the Android manifest.
3068     * <p>During the first boot, attempt to uncompress and install the full application. If
3069     * the application can't be installed for any reason, disable the stub and prevent
3070     * uncompressing the full application during future boots.
3071     * <p>In order to forcefully attempt an installation of a full application, go to app
3072     * settings and enable the application.
3073     */
3074    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3075        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3076            final String pkgName = stubSystemApps.get(i);
3077            // skip if the system package is already disabled
3078            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3079                stubSystemApps.remove(i);
3080                continue;
3081            }
3082            // skip if the package isn't installed (?!); this should never happen
3083            final PackageParser.Package pkg = mPackages.get(pkgName);
3084            if (pkg == null) {
3085                stubSystemApps.remove(i);
3086                continue;
3087            }
3088            // skip if the package has been disabled by the user
3089            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3090            if (ps != null) {
3091                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3092                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3093                    stubSystemApps.remove(i);
3094                    continue;
3095                }
3096            }
3097
3098            if (DEBUG_COMPRESSION) {
3099                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3100            }
3101
3102            // uncompress the binary to its eventual destination on /data
3103            final File scanFile = decompressPackage(pkg);
3104            if (scanFile == null) {
3105                continue;
3106            }
3107
3108            // install the package to replace the stub on /system
3109            try {
3110                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3111                removePackageLI(pkg, true /*chatty*/);
3112                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3113                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3114                        UserHandle.USER_SYSTEM, "android");
3115                stubSystemApps.remove(i);
3116                continue;
3117            } catch (PackageManagerException e) {
3118                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3119            }
3120
3121            // any failed attempt to install the package will be cleaned up later
3122        }
3123
3124        // disable any stub still left; these failed to install the full application
3125        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3126            final String pkgName = stubSystemApps.get(i);
3127            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3128            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3129                    UserHandle.USER_SYSTEM, "android");
3130            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3131        }
3132    }
3133
3134    private int decompressFile(File srcFile, File dstFile) throws ErrnoException {
3135        if (DEBUG_COMPRESSION) {
3136            Slog.i(TAG, "Decompress file"
3137                    + "; src: " + srcFile.getAbsolutePath()
3138                    + ", dst: " + dstFile.getAbsolutePath());
3139        }
3140        try (
3141                InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile));
3142                OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/);
3143        ) {
3144            Streams.copy(fileIn, fileOut);
3145            Os.chmod(dstFile.getAbsolutePath(), 0644);
3146            return PackageManager.INSTALL_SUCCEEDED;
3147        } catch (IOException e) {
3148            logCriticalInfo(Log.ERROR, "Failed to decompress file"
3149                    + "; src: " + srcFile.getAbsolutePath()
3150                    + ", dst: " + dstFile.getAbsolutePath());
3151        }
3152        return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3153    }
3154
3155    private File[] getCompressedFiles(String codePath) {
3156        final File stubCodePath = new File(codePath);
3157        final String stubName = stubCodePath.getName();
3158
3159        // The layout of a compressed package on a given partition is as follows :
3160        //
3161        // Compressed artifacts:
3162        //
3163        // /partition/ModuleName/foo.gz
3164        // /partation/ModuleName/bar.gz
3165        //
3166        // Stub artifact:
3167        //
3168        // /partition/ModuleName-Stub/ModuleName-Stub.apk
3169        //
3170        // In other words, stub is on the same partition as the compressed artifacts
3171        // and in a directory that's suffixed with "-Stub".
3172        int idx = stubName.lastIndexOf(STUB_SUFFIX);
3173        if (idx < 0 || (stubName.length() != (idx + STUB_SUFFIX.length()))) {
3174            return null;
3175        }
3176
3177        final File stubParentDir = stubCodePath.getParentFile();
3178        if (stubParentDir == null) {
3179            Slog.e(TAG, "Unable to determine stub parent dir for codePath: " + codePath);
3180            return null;
3181        }
3182
3183        final File compressedPath = new File(stubParentDir, stubName.substring(0, idx));
3184        final File[] files = compressedPath.listFiles(new FilenameFilter() {
3185            @Override
3186            public boolean accept(File dir, String name) {
3187                return name.toLowerCase().endsWith(COMPRESSED_EXTENSION);
3188            }
3189        });
3190
3191        if (DEBUG_COMPRESSION && files != null && files.length > 0) {
3192            Slog.i(TAG, "getCompressedFiles[" + codePath + "]: " + Arrays.toString(files));
3193        }
3194
3195        return files;
3196    }
3197
3198    private boolean compressedFileExists(String codePath) {
3199        final File[] compressedFiles = getCompressedFiles(codePath);
3200        return compressedFiles != null && compressedFiles.length > 0;
3201    }
3202
3203    /**
3204     * Decompresses the given package on the system image onto
3205     * the /data partition.
3206     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3207     */
3208    private File decompressPackage(PackageParser.Package pkg) {
3209        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3210        if (compressedFiles == null || compressedFiles.length == 0) {
3211            if (DEBUG_COMPRESSION) {
3212                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3213            }
3214            return null;
3215        }
3216        final File dstCodePath =
3217                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3218        int ret = PackageManager.INSTALL_SUCCEEDED;
3219        try {
3220            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3221            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3222            for (File srcFile : compressedFiles) {
3223                final String srcFileName = srcFile.getName();
3224                final String dstFileName = srcFileName.substring(
3225                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3226                final File dstFile = new File(dstCodePath, dstFileName);
3227                ret = decompressFile(srcFile, dstFile);
3228                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3229                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3230                            + "; pkg: " + pkg.packageName
3231                            + ", file: " + dstFileName);
3232                    break;
3233                }
3234            }
3235        } catch (ErrnoException e) {
3236            logCriticalInfo(Log.ERROR, "Failed to decompress"
3237                    + "; pkg: " + pkg.packageName
3238                    + ", err: " + e.errno);
3239        }
3240        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3241            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3242            NativeLibraryHelper.Handle handle = null;
3243            try {
3244                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3245                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3246                        null /*abiOverride*/);
3247            } catch (IOException e) {
3248                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3249                        + "; pkg: " + pkg.packageName);
3250                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3251            } finally {
3252                IoUtils.closeQuietly(handle);
3253            }
3254        }
3255        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3256            if (dstCodePath == null || !dstCodePath.exists()) {
3257                return null;
3258            }
3259            removeCodePathLI(dstCodePath);
3260            return null;
3261        }
3262
3263        // If we have a profile for a compressed APK, copy it to the reference location.
3264        // Since the package is the stub one, remove the stub suffix to get the normal package and
3265        // APK name.
3266        File profileFile = new File(getPrebuildProfilePath(pkg).replace(STUB_SUFFIX, ""));
3267        if (profileFile.exists()) {
3268            try {
3269                // We could also do this lazily before calling dexopt in
3270                // PackageDexOptimizer to prevent this happening on first boot. The issue
3271                // is that we don't have a good way to say "do this only once".
3272                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
3273                        pkg.applicationInfo.uid, pkg.packageName)) {
3274                    Log.e(TAG, "decompressPackage failed to copy system profile!");
3275                }
3276            } catch (Exception e) {
3277                Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ", e);
3278            }
3279        }
3280        return dstCodePath;
3281    }
3282
3283    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3284        // we're only interested in updating the installer appliction when 1) it's not
3285        // already set or 2) the modified package is the installer
3286        if (mInstantAppInstallerActivity != null
3287                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3288                        .equals(modifiedPackage)) {
3289            return;
3290        }
3291        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3292    }
3293
3294    private static File preparePackageParserCache(boolean isUpgrade) {
3295        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3296            return null;
3297        }
3298
3299        // Disable package parsing on eng builds to allow for faster incremental development.
3300        if (Build.IS_ENG) {
3301            return null;
3302        }
3303
3304        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3305            Slog.i(TAG, "Disabling package parser cache due to system property.");
3306            return null;
3307        }
3308
3309        // The base directory for the package parser cache lives under /data/system/.
3310        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3311                "package_cache");
3312        if (cacheBaseDir == null) {
3313            return null;
3314        }
3315
3316        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3317        // This also serves to "GC" unused entries when the package cache version changes (which
3318        // can only happen during upgrades).
3319        if (isUpgrade) {
3320            FileUtils.deleteContents(cacheBaseDir);
3321        }
3322
3323
3324        // Return the versioned package cache directory. This is something like
3325        // "/data/system/package_cache/1"
3326        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3327
3328        // The following is a workaround to aid development on non-numbered userdebug
3329        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3330        // the system partition is newer.
3331        //
3332        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3333        // that starts with "eng." to signify that this is an engineering build and not
3334        // destined for release.
3335        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3336            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3337
3338            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3339            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3340            // in general and should not be used for production changes. In this specific case,
3341            // we know that they will work.
3342            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3343            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3344                FileUtils.deleteContents(cacheBaseDir);
3345                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3346            }
3347        }
3348
3349        return cacheDir;
3350    }
3351
3352    @Override
3353    public boolean isFirstBoot() {
3354        // allow instant applications
3355        return mFirstBoot;
3356    }
3357
3358    @Override
3359    public boolean isOnlyCoreApps() {
3360        // allow instant applications
3361        return mOnlyCore;
3362    }
3363
3364    @Override
3365    public boolean isUpgrade() {
3366        // allow instant applications
3367        return mIsUpgrade;
3368    }
3369
3370    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3371        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3372
3373        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3374                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3375                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3376        if (matches.size() == 1) {
3377            return matches.get(0).getComponentInfo().packageName;
3378        } else if (matches.size() == 0) {
3379            Log.e(TAG, "There should probably be a verifier, but, none were found");
3380            return null;
3381        }
3382        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3383    }
3384
3385    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3386        synchronized (mPackages) {
3387            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3388            if (libraryEntry == null) {
3389                throw new IllegalStateException("Missing required shared library:" + name);
3390            }
3391            return libraryEntry.apk;
3392        }
3393    }
3394
3395    private @NonNull String getRequiredInstallerLPr() {
3396        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3397        intent.addCategory(Intent.CATEGORY_DEFAULT);
3398        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3399
3400        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3401                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3402                UserHandle.USER_SYSTEM);
3403        if (matches.size() == 1) {
3404            ResolveInfo resolveInfo = matches.get(0);
3405            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3406                throw new RuntimeException("The installer must be a privileged app");
3407            }
3408            return matches.get(0).getComponentInfo().packageName;
3409        } else {
3410            throw new RuntimeException("There must be exactly one installer; found " + matches);
3411        }
3412    }
3413
3414    private @NonNull String getRequiredUninstallerLPr() {
3415        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3416        intent.addCategory(Intent.CATEGORY_DEFAULT);
3417        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3418
3419        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3420                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3421                UserHandle.USER_SYSTEM);
3422        if (resolveInfo == null ||
3423                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3424            throw new RuntimeException("There must be exactly one uninstaller; found "
3425                    + resolveInfo);
3426        }
3427        return resolveInfo.getComponentInfo().packageName;
3428    }
3429
3430    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3431        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3432
3433        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3434                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3435                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3436        ResolveInfo best = null;
3437        final int N = matches.size();
3438        for (int i = 0; i < N; i++) {
3439            final ResolveInfo cur = matches.get(i);
3440            final String packageName = cur.getComponentInfo().packageName;
3441            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3442                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3443                continue;
3444            }
3445
3446            if (best == null || cur.priority > best.priority) {
3447                best = cur;
3448            }
3449        }
3450
3451        if (best != null) {
3452            return best.getComponentInfo().getComponentName();
3453        }
3454        Slog.w(TAG, "Intent filter verifier not found");
3455        return null;
3456    }
3457
3458    @Override
3459    public @Nullable ComponentName getInstantAppResolverComponent() {
3460        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3461            return null;
3462        }
3463        synchronized (mPackages) {
3464            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3465            if (instantAppResolver == null) {
3466                return null;
3467            }
3468            return instantAppResolver.first;
3469        }
3470    }
3471
3472    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3473        final String[] packageArray =
3474                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3475        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3476            if (DEBUG_EPHEMERAL) {
3477                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3478            }
3479            return null;
3480        }
3481
3482        final int callingUid = Binder.getCallingUid();
3483        final int resolveFlags =
3484                MATCH_DIRECT_BOOT_AWARE
3485                | MATCH_DIRECT_BOOT_UNAWARE
3486                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3487        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3488        final Intent resolverIntent = new Intent(actionName);
3489        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3490                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3491        // temporarily look for the old action
3492        if (resolvers.size() == 0) {
3493            if (DEBUG_EPHEMERAL) {
3494                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3495            }
3496            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3497            resolverIntent.setAction(actionName);
3498            resolvers = queryIntentServicesInternal(resolverIntent, null,
3499                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3500        }
3501        final int N = resolvers.size();
3502        if (N == 0) {
3503            if (DEBUG_EPHEMERAL) {
3504                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3505            }
3506            return null;
3507        }
3508
3509        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3510        for (int i = 0; i < N; i++) {
3511            final ResolveInfo info = resolvers.get(i);
3512
3513            if (info.serviceInfo == null) {
3514                continue;
3515            }
3516
3517            final String packageName = info.serviceInfo.packageName;
3518            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3519                if (DEBUG_EPHEMERAL) {
3520                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3521                            + " pkg: " + packageName + ", info:" + info);
3522                }
3523                continue;
3524            }
3525
3526            if (DEBUG_EPHEMERAL) {
3527                Slog.v(TAG, "Ephemeral resolver found;"
3528                        + " pkg: " + packageName + ", info:" + info);
3529            }
3530            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3531        }
3532        if (DEBUG_EPHEMERAL) {
3533            Slog.v(TAG, "Ephemeral resolver NOT found");
3534        }
3535        return null;
3536    }
3537
3538    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3539        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3540        intent.addCategory(Intent.CATEGORY_DEFAULT);
3541        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3542
3543        final int resolveFlags =
3544                MATCH_DIRECT_BOOT_AWARE
3545                | MATCH_DIRECT_BOOT_UNAWARE
3546                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3547        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3548                resolveFlags, UserHandle.USER_SYSTEM);
3549        // temporarily look for the old action
3550        if (matches.isEmpty()) {
3551            if (DEBUG_EPHEMERAL) {
3552                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3553            }
3554            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3555            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3556                    resolveFlags, UserHandle.USER_SYSTEM);
3557        }
3558        Iterator<ResolveInfo> iter = matches.iterator();
3559        while (iter.hasNext()) {
3560            final ResolveInfo rInfo = iter.next();
3561            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3562            if (ps != null) {
3563                final PermissionsState permissionsState = ps.getPermissionsState();
3564                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3565                    continue;
3566                }
3567            }
3568            iter.remove();
3569        }
3570        if (matches.size() == 0) {
3571            return null;
3572        } else if (matches.size() == 1) {
3573            return (ActivityInfo) matches.get(0).getComponentInfo();
3574        } else {
3575            throw new RuntimeException(
3576                    "There must be at most one ephemeral installer; found " + matches);
3577        }
3578    }
3579
3580    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3581            @NonNull ComponentName resolver) {
3582        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3583                .addCategory(Intent.CATEGORY_DEFAULT)
3584                .setPackage(resolver.getPackageName());
3585        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3586        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3587                UserHandle.USER_SYSTEM);
3588        // temporarily look for the old action
3589        if (matches.isEmpty()) {
3590            if (DEBUG_EPHEMERAL) {
3591                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3592            }
3593            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3594            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3595                    UserHandle.USER_SYSTEM);
3596        }
3597        if (matches.isEmpty()) {
3598            return null;
3599        }
3600        return matches.get(0).getComponentInfo().getComponentName();
3601    }
3602
3603    private void primeDomainVerificationsLPw(int userId) {
3604        if (DEBUG_DOMAIN_VERIFICATION) {
3605            Slog.d(TAG, "Priming domain verifications in user " + userId);
3606        }
3607
3608        SystemConfig systemConfig = SystemConfig.getInstance();
3609        ArraySet<String> packages = systemConfig.getLinkedApps();
3610
3611        for (String packageName : packages) {
3612            PackageParser.Package pkg = mPackages.get(packageName);
3613            if (pkg != null) {
3614                if (!pkg.isSystemApp()) {
3615                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3616                    continue;
3617                }
3618
3619                ArraySet<String> domains = null;
3620                for (PackageParser.Activity a : pkg.activities) {
3621                    for (ActivityIntentInfo filter : a.intents) {
3622                        if (hasValidDomains(filter)) {
3623                            if (domains == null) {
3624                                domains = new ArraySet<String>();
3625                            }
3626                            domains.addAll(filter.getHostsList());
3627                        }
3628                    }
3629                }
3630
3631                if (domains != null && domains.size() > 0) {
3632                    if (DEBUG_DOMAIN_VERIFICATION) {
3633                        Slog.v(TAG, "      + " + packageName);
3634                    }
3635                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3636                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3637                    // and then 'always' in the per-user state actually used for intent resolution.
3638                    final IntentFilterVerificationInfo ivi;
3639                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3640                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3641                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3642                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3643                } else {
3644                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3645                            + "' does not handle web links");
3646                }
3647            } else {
3648                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3649            }
3650        }
3651
3652        scheduleWritePackageRestrictionsLocked(userId);
3653        scheduleWriteSettingsLocked();
3654    }
3655
3656    private void applyFactoryDefaultBrowserLPw(int userId) {
3657        // The default browser app's package name is stored in a string resource,
3658        // with a product-specific overlay used for vendor customization.
3659        String browserPkg = mContext.getResources().getString(
3660                com.android.internal.R.string.default_browser);
3661        if (!TextUtils.isEmpty(browserPkg)) {
3662            // non-empty string => required to be a known package
3663            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3664            if (ps == null) {
3665                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3666                browserPkg = null;
3667            } else {
3668                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3669            }
3670        }
3671
3672        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3673        // default.  If there's more than one, just leave everything alone.
3674        if (browserPkg == null) {
3675            calculateDefaultBrowserLPw(userId);
3676        }
3677    }
3678
3679    private void calculateDefaultBrowserLPw(int userId) {
3680        List<String> allBrowsers = resolveAllBrowserApps(userId);
3681        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3682        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3683    }
3684
3685    private List<String> resolveAllBrowserApps(int userId) {
3686        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3687        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3688                PackageManager.MATCH_ALL, userId);
3689
3690        final int count = list.size();
3691        List<String> result = new ArrayList<String>(count);
3692        for (int i=0; i<count; i++) {
3693            ResolveInfo info = list.get(i);
3694            if (info.activityInfo == null
3695                    || !info.handleAllWebDataURI
3696                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3697                    || result.contains(info.activityInfo.packageName)) {
3698                continue;
3699            }
3700            result.add(info.activityInfo.packageName);
3701        }
3702
3703        return result;
3704    }
3705
3706    private boolean packageIsBrowser(String packageName, int userId) {
3707        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3708                PackageManager.MATCH_ALL, userId);
3709        final int N = list.size();
3710        for (int i = 0; i < N; i++) {
3711            ResolveInfo info = list.get(i);
3712            if (packageName.equals(info.activityInfo.packageName)) {
3713                return true;
3714            }
3715        }
3716        return false;
3717    }
3718
3719    private void checkDefaultBrowser() {
3720        final int myUserId = UserHandle.myUserId();
3721        final String packageName = getDefaultBrowserPackageName(myUserId);
3722        if (packageName != null) {
3723            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3724            if (info == null) {
3725                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3726                synchronized (mPackages) {
3727                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3728                }
3729            }
3730        }
3731    }
3732
3733    @Override
3734    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3735            throws RemoteException {
3736        try {
3737            return super.onTransact(code, data, reply, flags);
3738        } catch (RuntimeException e) {
3739            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3740                Slog.wtf(TAG, "Package Manager Crash", e);
3741            }
3742            throw e;
3743        }
3744    }
3745
3746    static int[] appendInts(int[] cur, int[] add) {
3747        if (add == null) return cur;
3748        if (cur == null) return add;
3749        final int N = add.length;
3750        for (int i=0; i<N; i++) {
3751            cur = appendInt(cur, add[i]);
3752        }
3753        return cur;
3754    }
3755
3756    /**
3757     * Returns whether or not a full application can see an instant application.
3758     * <p>
3759     * Currently, there are three cases in which this can occur:
3760     * <ol>
3761     * <li>The calling application is a "special" process. The special
3762     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3763     *     and {@code 0}</li>
3764     * <li>The calling application has the permission
3765     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3766     * <li>The calling application is the default launcher on the
3767     *     system partition.</li>
3768     * </ol>
3769     */
3770    private boolean canViewInstantApps(int callingUid, int userId) {
3771        if (callingUid == Process.SYSTEM_UID
3772                || callingUid == Process.SHELL_UID
3773                || callingUid == Process.ROOT_UID) {
3774            return true;
3775        }
3776        if (mContext.checkCallingOrSelfPermission(
3777                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3778            return true;
3779        }
3780        if (mContext.checkCallingOrSelfPermission(
3781                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3782            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3783            if (homeComponent != null
3784                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3785                return true;
3786            }
3787        }
3788        return false;
3789    }
3790
3791    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3792        if (!sUserManager.exists(userId)) return null;
3793        if (ps == null) {
3794            return null;
3795        }
3796        PackageParser.Package p = ps.pkg;
3797        if (p == null) {
3798            return null;
3799        }
3800        final int callingUid = Binder.getCallingUid();
3801        // Filter out ephemeral app metadata:
3802        //   * The system/shell/root can see metadata for any app
3803        //   * An installed app can see metadata for 1) other installed apps
3804        //     and 2) ephemeral apps that have explicitly interacted with it
3805        //   * Ephemeral apps can only see their own data and exposed installed apps
3806        //   * Holding a signature permission allows seeing instant apps
3807        if (filterAppAccessLPr(ps, callingUid, userId)) {
3808            return null;
3809        }
3810
3811        final PermissionsState permissionsState = ps.getPermissionsState();
3812
3813        // Compute GIDs only if requested
3814        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3815                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3816        // Compute granted permissions only if package has requested permissions
3817        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3818                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3819        final PackageUserState state = ps.readUserState(userId);
3820
3821        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3822                && ps.isSystem()) {
3823            flags |= MATCH_ANY_USER;
3824        }
3825
3826        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3827                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3828
3829        if (packageInfo == null) {
3830            return null;
3831        }
3832
3833        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3834                resolveExternalPackageNameLPr(p);
3835
3836        return packageInfo;
3837    }
3838
3839    @Override
3840    public void checkPackageStartable(String packageName, int userId) {
3841        final int callingUid = Binder.getCallingUid();
3842        if (getInstantAppPackageName(callingUid) != null) {
3843            throw new SecurityException("Instant applications don't have access to this method");
3844        }
3845        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3846        synchronized (mPackages) {
3847            final PackageSetting ps = mSettings.mPackages.get(packageName);
3848            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3849                throw new SecurityException("Package " + packageName + " was not found!");
3850            }
3851
3852            if (!ps.getInstalled(userId)) {
3853                throw new SecurityException(
3854                        "Package " + packageName + " was not installed for user " + userId + "!");
3855            }
3856
3857            if (mSafeMode && !ps.isSystem()) {
3858                throw new SecurityException("Package " + packageName + " not a system app!");
3859            }
3860
3861            if (mFrozenPackages.contains(packageName)) {
3862                throw new SecurityException("Package " + packageName + " is currently frozen!");
3863            }
3864
3865            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3866                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3867            }
3868        }
3869    }
3870
3871    @Override
3872    public boolean isPackageAvailable(String packageName, int userId) {
3873        if (!sUserManager.exists(userId)) return false;
3874        final int callingUid = Binder.getCallingUid();
3875        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3876                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3877        synchronized (mPackages) {
3878            PackageParser.Package p = mPackages.get(packageName);
3879            if (p != null) {
3880                final PackageSetting ps = (PackageSetting) p.mExtras;
3881                if (filterAppAccessLPr(ps, callingUid, userId)) {
3882                    return false;
3883                }
3884                if (ps != null) {
3885                    final PackageUserState state = ps.readUserState(userId);
3886                    if (state != null) {
3887                        return PackageParser.isAvailable(state);
3888                    }
3889                }
3890            }
3891        }
3892        return false;
3893    }
3894
3895    @Override
3896    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3897        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3898                flags, Binder.getCallingUid(), userId);
3899    }
3900
3901    @Override
3902    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3903            int flags, int userId) {
3904        return getPackageInfoInternal(versionedPackage.getPackageName(),
3905                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3906    }
3907
3908    /**
3909     * Important: The provided filterCallingUid is used exclusively to filter out packages
3910     * that can be seen based on user state. It's typically the original caller uid prior
3911     * to clearing. Because it can only be provided by trusted code, it's value can be
3912     * trusted and will be used as-is; unlike userId which will be validated by this method.
3913     */
3914    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3915            int flags, int filterCallingUid, int userId) {
3916        if (!sUserManager.exists(userId)) return null;
3917        flags = updateFlagsForPackage(flags, userId, packageName);
3918        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
3919                false /* requireFullPermission */, false /* checkShell */, "get package info");
3920
3921        // reader
3922        synchronized (mPackages) {
3923            // Normalize package name to handle renamed packages and static libs
3924            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3925
3926            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3927            if (matchFactoryOnly) {
3928                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3929                if (ps != null) {
3930                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3931                        return null;
3932                    }
3933                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3934                        return null;
3935                    }
3936                    return generatePackageInfo(ps, flags, userId);
3937                }
3938            }
3939
3940            PackageParser.Package p = mPackages.get(packageName);
3941            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3942                return null;
3943            }
3944            if (DEBUG_PACKAGE_INFO)
3945                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3946            if (p != null) {
3947                final PackageSetting ps = (PackageSetting) p.mExtras;
3948                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3949                    return null;
3950                }
3951                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3952                    return null;
3953                }
3954                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3955            }
3956            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3957                final PackageSetting ps = mSettings.mPackages.get(packageName);
3958                if (ps == null) return null;
3959                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3960                    return null;
3961                }
3962                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3963                    return null;
3964                }
3965                return generatePackageInfo(ps, flags, userId);
3966            }
3967        }
3968        return null;
3969    }
3970
3971    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3972        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3973            return true;
3974        }
3975        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3976            return true;
3977        }
3978        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3979            return true;
3980        }
3981        return false;
3982    }
3983
3984    private boolean isComponentVisibleToInstantApp(
3985            @Nullable ComponentName component, @ComponentType int type) {
3986        if (type == TYPE_ACTIVITY) {
3987            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3988            return activity != null
3989                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3990                    : false;
3991        } else if (type == TYPE_RECEIVER) {
3992            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3993            return activity != null
3994                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3995                    : false;
3996        } else if (type == TYPE_SERVICE) {
3997            final PackageParser.Service service = mServices.mServices.get(component);
3998            return service != null
3999                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4000                    : false;
4001        } else if (type == TYPE_PROVIDER) {
4002            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4003            return provider != null
4004                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4005                    : false;
4006        } else if (type == TYPE_UNKNOWN) {
4007            return isComponentVisibleToInstantApp(component);
4008        }
4009        return false;
4010    }
4011
4012    /**
4013     * Returns whether or not access to the application should be filtered.
4014     * <p>
4015     * Access may be limited based upon whether the calling or target applications
4016     * are instant applications.
4017     *
4018     * @see #canAccessInstantApps(int)
4019     */
4020    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4021            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4022        // if we're in an isolated process, get the real calling UID
4023        if (Process.isIsolated(callingUid)) {
4024            callingUid = mIsolatedOwners.get(callingUid);
4025        }
4026        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4027        final boolean callerIsInstantApp = instantAppPkgName != null;
4028        if (ps == null) {
4029            if (callerIsInstantApp) {
4030                // pretend the application exists, but, needs to be filtered
4031                return true;
4032            }
4033            return false;
4034        }
4035        // if the target and caller are the same application, don't filter
4036        if (isCallerSameApp(ps.name, callingUid)) {
4037            return false;
4038        }
4039        if (callerIsInstantApp) {
4040            // request for a specific component; if it hasn't been explicitly exposed, filter
4041            if (component != null) {
4042                return !isComponentVisibleToInstantApp(component, componentType);
4043            }
4044            // request for application; if no components have been explicitly exposed, filter
4045            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4046        }
4047        if (ps.getInstantApp(userId)) {
4048            // caller can see all components of all instant applications, don't filter
4049            if (canViewInstantApps(callingUid, userId)) {
4050                return false;
4051            }
4052            // request for a specific instant application component, filter
4053            if (component != null) {
4054                return true;
4055            }
4056            // request for an instant application; if the caller hasn't been granted access, filter
4057            return !mInstantAppRegistry.isInstantAccessGranted(
4058                    userId, UserHandle.getAppId(callingUid), ps.appId);
4059        }
4060        return false;
4061    }
4062
4063    /**
4064     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4065     */
4066    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4067        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4068    }
4069
4070    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4071            int flags) {
4072        // Callers can access only the libs they depend on, otherwise they need to explicitly
4073        // ask for the shared libraries given the caller is allowed to access all static libs.
4074        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4075            // System/shell/root get to see all static libs
4076            final int appId = UserHandle.getAppId(uid);
4077            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4078                    || appId == Process.ROOT_UID) {
4079                return false;
4080            }
4081        }
4082
4083        // No package means no static lib as it is always on internal storage
4084        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4085            return false;
4086        }
4087
4088        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4089                ps.pkg.staticSharedLibVersion);
4090        if (libEntry == null) {
4091            return false;
4092        }
4093
4094        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4095        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4096        if (uidPackageNames == null) {
4097            return true;
4098        }
4099
4100        for (String uidPackageName : uidPackageNames) {
4101            if (ps.name.equals(uidPackageName)) {
4102                return false;
4103            }
4104            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4105            if (uidPs != null) {
4106                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4107                        libEntry.info.getName());
4108                if (index < 0) {
4109                    continue;
4110                }
4111                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4112                    return false;
4113                }
4114            }
4115        }
4116        return true;
4117    }
4118
4119    @Override
4120    public String[] currentToCanonicalPackageNames(String[] names) {
4121        final int callingUid = Binder.getCallingUid();
4122        if (getInstantAppPackageName(callingUid) != null) {
4123            return names;
4124        }
4125        final String[] out = new String[names.length];
4126        // reader
4127        synchronized (mPackages) {
4128            final int callingUserId = UserHandle.getUserId(callingUid);
4129            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4130            for (int i=names.length-1; i>=0; i--) {
4131                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4132                boolean translateName = false;
4133                if (ps != null && ps.realName != null) {
4134                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4135                    translateName = !targetIsInstantApp
4136                            || canViewInstantApps
4137                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4138                                    UserHandle.getAppId(callingUid), ps.appId);
4139                }
4140                out[i] = translateName ? ps.realName : names[i];
4141            }
4142        }
4143        return out;
4144    }
4145
4146    @Override
4147    public String[] canonicalToCurrentPackageNames(String[] names) {
4148        final int callingUid = Binder.getCallingUid();
4149        if (getInstantAppPackageName(callingUid) != null) {
4150            return names;
4151        }
4152        final String[] out = new String[names.length];
4153        // reader
4154        synchronized (mPackages) {
4155            final int callingUserId = UserHandle.getUserId(callingUid);
4156            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4157            for (int i=names.length-1; i>=0; i--) {
4158                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4159                boolean translateName = false;
4160                if (cur != null) {
4161                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4162                    final boolean targetIsInstantApp =
4163                            ps != null && ps.getInstantApp(callingUserId);
4164                    translateName = !targetIsInstantApp
4165                            || canViewInstantApps
4166                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4167                                    UserHandle.getAppId(callingUid), ps.appId);
4168                }
4169                out[i] = translateName ? cur : names[i];
4170            }
4171        }
4172        return out;
4173    }
4174
4175    @Override
4176    public int getPackageUid(String packageName, int flags, int userId) {
4177        if (!sUserManager.exists(userId)) return -1;
4178        final int callingUid = Binder.getCallingUid();
4179        flags = updateFlagsForPackage(flags, userId, packageName);
4180        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4181                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4182
4183        // reader
4184        synchronized (mPackages) {
4185            final PackageParser.Package p = mPackages.get(packageName);
4186            if (p != null && p.isMatch(flags)) {
4187                PackageSetting ps = (PackageSetting) p.mExtras;
4188                if (filterAppAccessLPr(ps, callingUid, userId)) {
4189                    return -1;
4190                }
4191                return UserHandle.getUid(userId, p.applicationInfo.uid);
4192            }
4193            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4194                final PackageSetting ps = mSettings.mPackages.get(packageName);
4195                if (ps != null && ps.isMatch(flags)
4196                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4197                    return UserHandle.getUid(userId, ps.appId);
4198                }
4199            }
4200        }
4201
4202        return -1;
4203    }
4204
4205    @Override
4206    public int[] getPackageGids(String packageName, int flags, int userId) {
4207        if (!sUserManager.exists(userId)) return null;
4208        final int callingUid = Binder.getCallingUid();
4209        flags = updateFlagsForPackage(flags, userId, packageName);
4210        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4211                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4212
4213        // reader
4214        synchronized (mPackages) {
4215            final PackageParser.Package p = mPackages.get(packageName);
4216            if (p != null && p.isMatch(flags)) {
4217                PackageSetting ps = (PackageSetting) p.mExtras;
4218                if (filterAppAccessLPr(ps, callingUid, userId)) {
4219                    return null;
4220                }
4221                // TODO: Shouldn't this be checking for package installed state for userId and
4222                // return null?
4223                return ps.getPermissionsState().computeGids(userId);
4224            }
4225            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4226                final PackageSetting ps = mSettings.mPackages.get(packageName);
4227                if (ps != null && ps.isMatch(flags)
4228                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4229                    return ps.getPermissionsState().computeGids(userId);
4230                }
4231            }
4232        }
4233
4234        return null;
4235    }
4236
4237    @Override
4238    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4239        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4240    }
4241
4242    @Override
4243    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4244            int flags) {
4245        // TODO Move this to PermissionManager when mPermissionGroups is moved there
4246        synchronized (mPackages) {
4247            if (groupName != null && !mPermissionGroups.containsKey(groupName)) {
4248                // This is thrown as NameNotFoundException
4249                return null;
4250            }
4251        }
4252        return new ParceledListSlice<>(
4253                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid()));
4254    }
4255
4256    @Override
4257    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4258        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4259            return null;
4260        }
4261        // reader
4262        synchronized (mPackages) {
4263            return PackageParser.generatePermissionGroupInfo(
4264                    mPermissionGroups.get(name), flags);
4265        }
4266    }
4267
4268    @Override
4269    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4270        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4271            return ParceledListSlice.emptyList();
4272        }
4273        // reader
4274        synchronized (mPackages) {
4275            final int N = mPermissionGroups.size();
4276            ArrayList<PermissionGroupInfo> out
4277                    = new ArrayList<PermissionGroupInfo>(N);
4278            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4279                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4280            }
4281            return new ParceledListSlice<>(out);
4282        }
4283    }
4284
4285    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4286            int filterCallingUid, int userId) {
4287        if (!sUserManager.exists(userId)) return null;
4288        PackageSetting ps = mSettings.mPackages.get(packageName);
4289        if (ps != null) {
4290            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4291                return null;
4292            }
4293            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4294                return null;
4295            }
4296            if (ps.pkg == null) {
4297                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4298                if (pInfo != null) {
4299                    return pInfo.applicationInfo;
4300                }
4301                return null;
4302            }
4303            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4304                    ps.readUserState(userId), userId);
4305            if (ai != null) {
4306                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4307            }
4308            return ai;
4309        }
4310        return null;
4311    }
4312
4313    @Override
4314    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4315        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4316    }
4317
4318    /**
4319     * Important: The provided filterCallingUid is used exclusively to filter out applications
4320     * that can be seen based on user state. It's typically the original caller uid prior
4321     * to clearing. Because it can only be provided by trusted code, it's value can be
4322     * trusted and will be used as-is; unlike userId which will be validated by this method.
4323     */
4324    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4325            int filterCallingUid, int userId) {
4326        if (!sUserManager.exists(userId)) return null;
4327        flags = updateFlagsForApplication(flags, userId, packageName);
4328        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4329                false /* requireFullPermission */, false /* checkShell */, "get application info");
4330
4331        // writer
4332        synchronized (mPackages) {
4333            // Normalize package name to handle renamed packages and static libs
4334            packageName = resolveInternalPackageNameLPr(packageName,
4335                    PackageManager.VERSION_CODE_HIGHEST);
4336
4337            PackageParser.Package p = mPackages.get(packageName);
4338            if (DEBUG_PACKAGE_INFO) Log.v(
4339                    TAG, "getApplicationInfo " + packageName
4340                    + ": " + p);
4341            if (p != null) {
4342                PackageSetting ps = mSettings.mPackages.get(packageName);
4343                if (ps == null) return null;
4344                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4345                    return null;
4346                }
4347                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4348                    return null;
4349                }
4350                // Note: isEnabledLP() does not apply here - always return info
4351                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4352                        p, flags, ps.readUserState(userId), userId);
4353                if (ai != null) {
4354                    ai.packageName = resolveExternalPackageNameLPr(p);
4355                }
4356                return ai;
4357            }
4358            if ("android".equals(packageName)||"system".equals(packageName)) {
4359                return mAndroidApplication;
4360            }
4361            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4362                // Already generates the external package name
4363                return generateApplicationInfoFromSettingsLPw(packageName,
4364                        flags, filterCallingUid, userId);
4365            }
4366        }
4367        return null;
4368    }
4369
4370    private String normalizePackageNameLPr(String packageName) {
4371        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4372        return normalizedPackageName != null ? normalizedPackageName : packageName;
4373    }
4374
4375    @Override
4376    public void deletePreloadsFileCache() {
4377        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4378            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4379        }
4380        File dir = Environment.getDataPreloadsFileCacheDirectory();
4381        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4382        FileUtils.deleteContents(dir);
4383    }
4384
4385    @Override
4386    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4387            final int storageFlags, final IPackageDataObserver observer) {
4388        mContext.enforceCallingOrSelfPermission(
4389                android.Manifest.permission.CLEAR_APP_CACHE, null);
4390        mHandler.post(() -> {
4391            boolean success = false;
4392            try {
4393                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4394                success = true;
4395            } catch (IOException e) {
4396                Slog.w(TAG, e);
4397            }
4398            if (observer != null) {
4399                try {
4400                    observer.onRemoveCompleted(null, success);
4401                } catch (RemoteException e) {
4402                    Slog.w(TAG, e);
4403                }
4404            }
4405        });
4406    }
4407
4408    @Override
4409    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4410            final int storageFlags, final IntentSender pi) {
4411        mContext.enforceCallingOrSelfPermission(
4412                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4413        mHandler.post(() -> {
4414            boolean success = false;
4415            try {
4416                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4417                success = true;
4418            } catch (IOException e) {
4419                Slog.w(TAG, e);
4420            }
4421            if (pi != null) {
4422                try {
4423                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4424                } catch (SendIntentException e) {
4425                    Slog.w(TAG, e);
4426                }
4427            }
4428        });
4429    }
4430
4431    /**
4432     * Blocking call to clear various types of cached data across the system
4433     * until the requested bytes are available.
4434     */
4435    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4436        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4437        final File file = storage.findPathForUuid(volumeUuid);
4438        if (file.getUsableSpace() >= bytes) return;
4439
4440        if (ENABLE_FREE_CACHE_V2) {
4441            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4442                    volumeUuid);
4443            final boolean aggressive = (storageFlags
4444                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4445            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4446
4447            // 1. Pre-flight to determine if we have any chance to succeed
4448            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4449            if (internalVolume && (aggressive || SystemProperties
4450                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4451                deletePreloadsFileCache();
4452                if (file.getUsableSpace() >= bytes) return;
4453            }
4454
4455            // 3. Consider parsed APK data (aggressive only)
4456            if (internalVolume && aggressive) {
4457                FileUtils.deleteContents(mCacheDir);
4458                if (file.getUsableSpace() >= bytes) return;
4459            }
4460
4461            // 4. Consider cached app data (above quotas)
4462            try {
4463                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4464                        Installer.FLAG_FREE_CACHE_V2);
4465            } catch (InstallerException ignored) {
4466            }
4467            if (file.getUsableSpace() >= bytes) return;
4468
4469            // 5. Consider shared libraries with refcount=0 and age>min cache period
4470            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4471                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4472                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4473                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4474                return;
4475            }
4476
4477            // 6. Consider dexopt output (aggressive only)
4478            // TODO: Implement
4479
4480            // 7. Consider installed instant apps unused longer than min cache period
4481            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4482                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4483                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4484                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4485                return;
4486            }
4487
4488            // 8. Consider cached app data (below quotas)
4489            try {
4490                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4491                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4492            } catch (InstallerException ignored) {
4493            }
4494            if (file.getUsableSpace() >= bytes) return;
4495
4496            // 9. Consider DropBox entries
4497            // TODO: Implement
4498
4499            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4500            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4501                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4502                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4503                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4504                return;
4505            }
4506        } else {
4507            try {
4508                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4509            } catch (InstallerException ignored) {
4510            }
4511            if (file.getUsableSpace() >= bytes) return;
4512        }
4513
4514        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4515    }
4516
4517    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4518            throws IOException {
4519        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4520        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4521
4522        List<VersionedPackage> packagesToDelete = null;
4523        final long now = System.currentTimeMillis();
4524
4525        synchronized (mPackages) {
4526            final int[] allUsers = sUserManager.getUserIds();
4527            final int libCount = mSharedLibraries.size();
4528            for (int i = 0; i < libCount; i++) {
4529                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4530                if (versionedLib == null) {
4531                    continue;
4532                }
4533                final int versionCount = versionedLib.size();
4534                for (int j = 0; j < versionCount; j++) {
4535                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4536                    // Skip packages that are not static shared libs.
4537                    if (!libInfo.isStatic()) {
4538                        break;
4539                    }
4540                    // Important: We skip static shared libs used for some user since
4541                    // in such a case we need to keep the APK on the device. The check for
4542                    // a lib being used for any user is performed by the uninstall call.
4543                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4544                    // Resolve the package name - we use synthetic package names internally
4545                    final String internalPackageName = resolveInternalPackageNameLPr(
4546                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4547                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4548                    // Skip unused static shared libs cached less than the min period
4549                    // to prevent pruning a lib needed by a subsequently installed package.
4550                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4551                        continue;
4552                    }
4553                    if (packagesToDelete == null) {
4554                        packagesToDelete = new ArrayList<>();
4555                    }
4556                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4557                            declaringPackage.getVersionCode()));
4558                }
4559            }
4560        }
4561
4562        if (packagesToDelete != null) {
4563            final int packageCount = packagesToDelete.size();
4564            for (int i = 0; i < packageCount; i++) {
4565                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4566                // Delete the package synchronously (will fail of the lib used for any user).
4567                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4568                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4569                                == PackageManager.DELETE_SUCCEEDED) {
4570                    if (volume.getUsableSpace() >= neededSpace) {
4571                        return true;
4572                    }
4573                }
4574            }
4575        }
4576
4577        return false;
4578    }
4579
4580    /**
4581     * Update given flags based on encryption status of current user.
4582     */
4583    private int updateFlags(int flags, int userId) {
4584        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4585                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4586            // Caller expressed an explicit opinion about what encryption
4587            // aware/unaware components they want to see, so fall through and
4588            // give them what they want
4589        } else {
4590            // Caller expressed no opinion, so match based on user state
4591            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4592                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4593            } else {
4594                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4595            }
4596        }
4597        return flags;
4598    }
4599
4600    private UserManagerInternal getUserManagerInternal() {
4601        if (mUserManagerInternal == null) {
4602            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4603        }
4604        return mUserManagerInternal;
4605    }
4606
4607    private DeviceIdleController.LocalService getDeviceIdleController() {
4608        if (mDeviceIdleController == null) {
4609            mDeviceIdleController =
4610                    LocalServices.getService(DeviceIdleController.LocalService.class);
4611        }
4612        return mDeviceIdleController;
4613    }
4614
4615    /**
4616     * Update given flags when being used to request {@link PackageInfo}.
4617     */
4618    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4619        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4620        boolean triaged = true;
4621        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4622                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4623            // Caller is asking for component details, so they'd better be
4624            // asking for specific encryption matching behavior, or be triaged
4625            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4626                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4627                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4628                triaged = false;
4629            }
4630        }
4631        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4632                | PackageManager.MATCH_SYSTEM_ONLY
4633                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4634            triaged = false;
4635        }
4636        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4637            mPermissionManager.enforceCrossUserPermission(
4638                    Binder.getCallingUid(), userId, false, false,
4639                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4640                    + Debug.getCallers(5));
4641        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4642                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4643            // If the caller wants all packages and has a restricted profile associated with it,
4644            // then match all users. This is to make sure that launchers that need to access work
4645            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4646            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4647            flags |= PackageManager.MATCH_ANY_USER;
4648        }
4649        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4650            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4651                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4652        }
4653        return updateFlags(flags, userId);
4654    }
4655
4656    /**
4657     * Update given flags when being used to request {@link ApplicationInfo}.
4658     */
4659    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4660        return updateFlagsForPackage(flags, userId, cookie);
4661    }
4662
4663    /**
4664     * Update given flags when being used to request {@link ComponentInfo}.
4665     */
4666    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4667        if (cookie instanceof Intent) {
4668            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4669                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4670            }
4671        }
4672
4673        boolean triaged = true;
4674        // Caller is asking for component details, so they'd better be
4675        // asking for specific encryption matching behavior, or be triaged
4676        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4677                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4678                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4679            triaged = false;
4680        }
4681        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4682            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4683                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4684        }
4685
4686        return updateFlags(flags, userId);
4687    }
4688
4689    /**
4690     * Update given intent when being used to request {@link ResolveInfo}.
4691     */
4692    private Intent updateIntentForResolve(Intent intent) {
4693        if (intent.getSelector() != null) {
4694            intent = intent.getSelector();
4695        }
4696        if (DEBUG_PREFERRED) {
4697            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4698        }
4699        return intent;
4700    }
4701
4702    /**
4703     * Update given flags when being used to request {@link ResolveInfo}.
4704     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4705     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4706     * flag set. However, this flag is only honoured in three circumstances:
4707     * <ul>
4708     * <li>when called from a system process</li>
4709     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4710     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4711     * action and a {@code android.intent.category.BROWSABLE} category</li>
4712     * </ul>
4713     */
4714    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4715        return updateFlagsForResolve(flags, userId, intent, callingUid,
4716                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4717    }
4718    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4719            boolean wantInstantApps) {
4720        return updateFlagsForResolve(flags, userId, intent, callingUid,
4721                wantInstantApps, false /*onlyExposedExplicitly*/);
4722    }
4723    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4724            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4725        // Safe mode means we shouldn't match any third-party components
4726        if (mSafeMode) {
4727            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4728        }
4729        if (getInstantAppPackageName(callingUid) != null) {
4730            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4731            if (onlyExposedExplicitly) {
4732                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4733            }
4734            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4735            flags |= PackageManager.MATCH_INSTANT;
4736        } else {
4737            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4738            final boolean allowMatchInstant =
4739                    (wantInstantApps
4740                            && Intent.ACTION_VIEW.equals(intent.getAction())
4741                            && hasWebURI(intent))
4742                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4743            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4744                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4745            if (!allowMatchInstant) {
4746                flags &= ~PackageManager.MATCH_INSTANT;
4747            }
4748        }
4749        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4750    }
4751
4752    @Override
4753    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4754        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4755    }
4756
4757    /**
4758     * Important: The provided filterCallingUid is used exclusively to filter out activities
4759     * that can be seen based on user state. It's typically the original caller uid prior
4760     * to clearing. Because it can only be provided by trusted code, it's value can be
4761     * trusted and will be used as-is; unlike userId which will be validated by this method.
4762     */
4763    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4764            int filterCallingUid, int userId) {
4765        if (!sUserManager.exists(userId)) return null;
4766        flags = updateFlagsForComponent(flags, userId, component);
4767        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4768                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4769        synchronized (mPackages) {
4770            PackageParser.Activity a = mActivities.mActivities.get(component);
4771
4772            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4773            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4774                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4775                if (ps == null) return null;
4776                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4777                    return null;
4778                }
4779                return PackageParser.generateActivityInfo(
4780                        a, flags, ps.readUserState(userId), userId);
4781            }
4782            if (mResolveComponentName.equals(component)) {
4783                return PackageParser.generateActivityInfo(
4784                        mResolveActivity, flags, new PackageUserState(), userId);
4785            }
4786        }
4787        return null;
4788    }
4789
4790    @Override
4791    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4792            String resolvedType) {
4793        synchronized (mPackages) {
4794            if (component.equals(mResolveComponentName)) {
4795                // The resolver supports EVERYTHING!
4796                return true;
4797            }
4798            final int callingUid = Binder.getCallingUid();
4799            final int callingUserId = UserHandle.getUserId(callingUid);
4800            PackageParser.Activity a = mActivities.mActivities.get(component);
4801            if (a == null) {
4802                return false;
4803            }
4804            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4805            if (ps == null) {
4806                return false;
4807            }
4808            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4809                return false;
4810            }
4811            for (int i=0; i<a.intents.size(); i++) {
4812                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4813                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4814                    return true;
4815                }
4816            }
4817            return false;
4818        }
4819    }
4820
4821    @Override
4822    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4823        if (!sUserManager.exists(userId)) return null;
4824        final int callingUid = Binder.getCallingUid();
4825        flags = updateFlagsForComponent(flags, userId, component);
4826        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4827                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4828        synchronized (mPackages) {
4829            PackageParser.Activity a = mReceivers.mActivities.get(component);
4830            if (DEBUG_PACKAGE_INFO) Log.v(
4831                TAG, "getReceiverInfo " + component + ": " + a);
4832            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4833                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4834                if (ps == null) return null;
4835                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4836                    return null;
4837                }
4838                return PackageParser.generateActivityInfo(
4839                        a, flags, ps.readUserState(userId), userId);
4840            }
4841        }
4842        return null;
4843    }
4844
4845    @Override
4846    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4847            int flags, int userId) {
4848        if (!sUserManager.exists(userId)) return null;
4849        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4850        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4851            return null;
4852        }
4853
4854        flags = updateFlagsForPackage(flags, userId, null);
4855
4856        final boolean canSeeStaticLibraries =
4857                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4858                        == PERMISSION_GRANTED
4859                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4860                        == PERMISSION_GRANTED
4861                || canRequestPackageInstallsInternal(packageName,
4862                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4863                        false  /* throwIfPermNotDeclared*/)
4864                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4865                        == PERMISSION_GRANTED;
4866
4867        synchronized (mPackages) {
4868            List<SharedLibraryInfo> result = null;
4869
4870            final int libCount = mSharedLibraries.size();
4871            for (int i = 0; i < libCount; i++) {
4872                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4873                if (versionedLib == null) {
4874                    continue;
4875                }
4876
4877                final int versionCount = versionedLib.size();
4878                for (int j = 0; j < versionCount; j++) {
4879                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4880                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4881                        break;
4882                    }
4883                    final long identity = Binder.clearCallingIdentity();
4884                    try {
4885                        PackageInfo packageInfo = getPackageInfoVersioned(
4886                                libInfo.getDeclaringPackage(), flags
4887                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4888                        if (packageInfo == null) {
4889                            continue;
4890                        }
4891                    } finally {
4892                        Binder.restoreCallingIdentity(identity);
4893                    }
4894
4895                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4896                            libInfo.getVersion(), libInfo.getType(),
4897                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4898                            flags, userId));
4899
4900                    if (result == null) {
4901                        result = new ArrayList<>();
4902                    }
4903                    result.add(resLibInfo);
4904                }
4905            }
4906
4907            return result != null ? new ParceledListSlice<>(result) : null;
4908        }
4909    }
4910
4911    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4912            SharedLibraryInfo libInfo, int flags, int userId) {
4913        List<VersionedPackage> versionedPackages = null;
4914        final int packageCount = mSettings.mPackages.size();
4915        for (int i = 0; i < packageCount; i++) {
4916            PackageSetting ps = mSettings.mPackages.valueAt(i);
4917
4918            if (ps == null) {
4919                continue;
4920            }
4921
4922            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4923                continue;
4924            }
4925
4926            final String libName = libInfo.getName();
4927            if (libInfo.isStatic()) {
4928                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4929                if (libIdx < 0) {
4930                    continue;
4931                }
4932                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4933                    continue;
4934                }
4935                if (versionedPackages == null) {
4936                    versionedPackages = new ArrayList<>();
4937                }
4938                // If the dependent is a static shared lib, use the public package name
4939                String dependentPackageName = ps.name;
4940                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4941                    dependentPackageName = ps.pkg.manifestPackageName;
4942                }
4943                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4944            } else if (ps.pkg != null) {
4945                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4946                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4947                    if (versionedPackages == null) {
4948                        versionedPackages = new ArrayList<>();
4949                    }
4950                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4951                }
4952            }
4953        }
4954
4955        return versionedPackages;
4956    }
4957
4958    @Override
4959    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4960        if (!sUserManager.exists(userId)) return null;
4961        final int callingUid = Binder.getCallingUid();
4962        flags = updateFlagsForComponent(flags, userId, component);
4963        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4964                false /* requireFullPermission */, false /* checkShell */, "get service info");
4965        synchronized (mPackages) {
4966            PackageParser.Service s = mServices.mServices.get(component);
4967            if (DEBUG_PACKAGE_INFO) Log.v(
4968                TAG, "getServiceInfo " + component + ": " + s);
4969            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4970                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4971                if (ps == null) return null;
4972                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4973                    return null;
4974                }
4975                return PackageParser.generateServiceInfo(
4976                        s, flags, ps.readUserState(userId), userId);
4977            }
4978        }
4979        return null;
4980    }
4981
4982    @Override
4983    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4984        if (!sUserManager.exists(userId)) return null;
4985        final int callingUid = Binder.getCallingUid();
4986        flags = updateFlagsForComponent(flags, userId, component);
4987        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4988                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4989        synchronized (mPackages) {
4990            PackageParser.Provider p = mProviders.mProviders.get(component);
4991            if (DEBUG_PACKAGE_INFO) Log.v(
4992                TAG, "getProviderInfo " + component + ": " + p);
4993            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4994                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4995                if (ps == null) return null;
4996                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4997                    return null;
4998                }
4999                return PackageParser.generateProviderInfo(
5000                        p, flags, ps.readUserState(userId), userId);
5001            }
5002        }
5003        return null;
5004    }
5005
5006    @Override
5007    public String[] getSystemSharedLibraryNames() {
5008        // allow instant applications
5009        synchronized (mPackages) {
5010            Set<String> libs = null;
5011            final int libCount = mSharedLibraries.size();
5012            for (int i = 0; i < libCount; i++) {
5013                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5014                if (versionedLib == null) {
5015                    continue;
5016                }
5017                final int versionCount = versionedLib.size();
5018                for (int j = 0; j < versionCount; j++) {
5019                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5020                    if (!libEntry.info.isStatic()) {
5021                        if (libs == null) {
5022                            libs = new ArraySet<>();
5023                        }
5024                        libs.add(libEntry.info.getName());
5025                        break;
5026                    }
5027                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5028                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5029                            UserHandle.getUserId(Binder.getCallingUid()),
5030                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5031                        if (libs == null) {
5032                            libs = new ArraySet<>();
5033                        }
5034                        libs.add(libEntry.info.getName());
5035                        break;
5036                    }
5037                }
5038            }
5039
5040            if (libs != null) {
5041                String[] libsArray = new String[libs.size()];
5042                libs.toArray(libsArray);
5043                return libsArray;
5044            }
5045
5046            return null;
5047        }
5048    }
5049
5050    @Override
5051    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5052        // allow instant applications
5053        synchronized (mPackages) {
5054            return mServicesSystemSharedLibraryPackageName;
5055        }
5056    }
5057
5058    @Override
5059    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5060        // allow instant applications
5061        synchronized (mPackages) {
5062            return mSharedSystemSharedLibraryPackageName;
5063        }
5064    }
5065
5066    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5067        for (int i = userList.length - 1; i >= 0; --i) {
5068            final int userId = userList[i];
5069            // don't add instant app to the list of updates
5070            if (pkgSetting.getInstantApp(userId)) {
5071                continue;
5072            }
5073            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5074            if (changedPackages == null) {
5075                changedPackages = new SparseArray<>();
5076                mChangedPackages.put(userId, changedPackages);
5077            }
5078            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5079            if (sequenceNumbers == null) {
5080                sequenceNumbers = new HashMap<>();
5081                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5082            }
5083            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5084            if (sequenceNumber != null) {
5085                changedPackages.remove(sequenceNumber);
5086            }
5087            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5088            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5089        }
5090        mChangedPackagesSequenceNumber++;
5091    }
5092
5093    @Override
5094    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5095        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5096            return null;
5097        }
5098        synchronized (mPackages) {
5099            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5100                return null;
5101            }
5102            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5103            if (changedPackages == null) {
5104                return null;
5105            }
5106            final List<String> packageNames =
5107                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5108            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5109                final String packageName = changedPackages.get(i);
5110                if (packageName != null) {
5111                    packageNames.add(packageName);
5112                }
5113            }
5114            return packageNames.isEmpty()
5115                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5116        }
5117    }
5118
5119    @Override
5120    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5121        // allow instant applications
5122        ArrayList<FeatureInfo> res;
5123        synchronized (mAvailableFeatures) {
5124            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5125            res.addAll(mAvailableFeatures.values());
5126        }
5127        final FeatureInfo fi = new FeatureInfo();
5128        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5129                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5130        res.add(fi);
5131
5132        return new ParceledListSlice<>(res);
5133    }
5134
5135    @Override
5136    public boolean hasSystemFeature(String name, int version) {
5137        // allow instant applications
5138        synchronized (mAvailableFeatures) {
5139            final FeatureInfo feat = mAvailableFeatures.get(name);
5140            if (feat == null) {
5141                return false;
5142            } else {
5143                return feat.version >= version;
5144            }
5145        }
5146    }
5147
5148    @Override
5149    public int checkPermission(String permName, String pkgName, int userId) {
5150        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5151    }
5152
5153    @Override
5154    public int checkUidPermission(String permName, int uid) {
5155        final int callingUid = Binder.getCallingUid();
5156        final int callingUserId = UserHandle.getUserId(callingUid);
5157        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5158        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5159        final int userId = UserHandle.getUserId(uid);
5160        if (!sUserManager.exists(userId)) {
5161            return PackageManager.PERMISSION_DENIED;
5162        }
5163
5164        synchronized (mPackages) {
5165            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5166            if (obj != null) {
5167                if (obj instanceof SharedUserSetting) {
5168                    if (isCallerInstantApp) {
5169                        return PackageManager.PERMISSION_DENIED;
5170                    }
5171                } else if (obj instanceof PackageSetting) {
5172                    final PackageSetting ps = (PackageSetting) obj;
5173                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5174                        return PackageManager.PERMISSION_DENIED;
5175                    }
5176                }
5177                final SettingBase settingBase = (SettingBase) obj;
5178                final PermissionsState permissionsState = settingBase.getPermissionsState();
5179                if (permissionsState.hasPermission(permName, userId)) {
5180                    if (isUidInstantApp) {
5181                        if (mSettings.mPermissions.isPermissionInstant(permName)) {
5182                            return PackageManager.PERMISSION_GRANTED;
5183                        }
5184                    } else {
5185                        return PackageManager.PERMISSION_GRANTED;
5186                    }
5187                }
5188                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5189                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5190                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5191                    return PackageManager.PERMISSION_GRANTED;
5192                }
5193            } else {
5194                ArraySet<String> perms = mSystemPermissions.get(uid);
5195                if (perms != null) {
5196                    if (perms.contains(permName)) {
5197                        return PackageManager.PERMISSION_GRANTED;
5198                    }
5199                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5200                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5201                        return PackageManager.PERMISSION_GRANTED;
5202                    }
5203                }
5204            }
5205        }
5206
5207        return PackageManager.PERMISSION_DENIED;
5208    }
5209
5210    @Override
5211    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5212        if (UserHandle.getCallingUserId() != userId) {
5213            mContext.enforceCallingPermission(
5214                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5215                    "isPermissionRevokedByPolicy for user " + userId);
5216        }
5217
5218        if (checkPermission(permission, packageName, userId)
5219                == PackageManager.PERMISSION_GRANTED) {
5220            return false;
5221        }
5222
5223        final int callingUid = Binder.getCallingUid();
5224        if (getInstantAppPackageName(callingUid) != null) {
5225            if (!isCallerSameApp(packageName, callingUid)) {
5226                return false;
5227            }
5228        } else {
5229            if (isInstantApp(packageName, userId)) {
5230                return false;
5231            }
5232        }
5233
5234        final long identity = Binder.clearCallingIdentity();
5235        try {
5236            final int flags = getPermissionFlags(permission, packageName, userId);
5237            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5238        } finally {
5239            Binder.restoreCallingIdentity(identity);
5240        }
5241    }
5242
5243    @Override
5244    public String getPermissionControllerPackageName() {
5245        synchronized (mPackages) {
5246            return mRequiredInstallerPackage;
5247        }
5248    }
5249
5250    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5251        return mPermissionManager.addDynamicPermission(
5252                info, async, getCallingUid(), new PermissionCallback() {
5253                    @Override
5254                    public void onPermissionChanged() {
5255                        if (!async) {
5256                            mSettings.writeLPr();
5257                        } else {
5258                            scheduleWriteSettingsLocked();
5259                        }
5260                    }
5261                });
5262    }
5263
5264    @Override
5265    public boolean addPermission(PermissionInfo info) {
5266        synchronized (mPackages) {
5267            return addDynamicPermission(info, false);
5268        }
5269    }
5270
5271    @Override
5272    public boolean addPermissionAsync(PermissionInfo info) {
5273        synchronized (mPackages) {
5274            return addDynamicPermission(info, true);
5275        }
5276    }
5277
5278    @Override
5279    public void removePermission(String permName) {
5280        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5281    }
5282
5283    @Override
5284    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5285        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5286                getCallingUid(), userId, mPermissionCallback);
5287    }
5288
5289    @Override
5290    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5291        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5292                getCallingUid(), userId, mPermissionCallback);
5293    }
5294
5295    /**
5296     * Get the first event id for the permission.
5297     *
5298     * <p>There are four events for each permission: <ul>
5299     *     <li>Request permission: first id + 0</li>
5300     *     <li>Grant permission: first id + 1</li>
5301     *     <li>Request for permission denied: first id + 2</li>
5302     *     <li>Revoke permission: first id + 3</li>
5303     * </ul></p>
5304     *
5305     * @param name name of the permission
5306     *
5307     * @return The first event id for the permission
5308     */
5309    private static int getBaseEventId(@NonNull String name) {
5310        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5311
5312        if (eventIdIndex == -1) {
5313            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5314                    || Build.IS_USER) {
5315                Log.i(TAG, "Unknown permission " + name);
5316
5317                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5318            } else {
5319                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5320                //
5321                // Also update
5322                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5323                // - metrics_constants.proto
5324                throw new IllegalStateException("Unknown permission " + name);
5325            }
5326        }
5327
5328        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5329    }
5330
5331    /**
5332     * Log that a permission was revoked.
5333     *
5334     * @param context Context of the caller
5335     * @param name name of the permission
5336     * @param packageName package permission if for
5337     */
5338    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5339            @NonNull String packageName) {
5340        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5341    }
5342
5343    /**
5344     * Log that a permission request was granted.
5345     *
5346     * @param context Context of the caller
5347     * @param name name of the permission
5348     * @param packageName package permission if for
5349     */
5350    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5351            @NonNull String packageName) {
5352        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5353    }
5354
5355    @Override
5356    public void resetRuntimePermissions() {
5357        mContext.enforceCallingOrSelfPermission(
5358                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5359                "revokeRuntimePermission");
5360
5361        int callingUid = Binder.getCallingUid();
5362        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5363            mContext.enforceCallingOrSelfPermission(
5364                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5365                    "resetRuntimePermissions");
5366        }
5367
5368        synchronized (mPackages) {
5369            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5370            for (int userId : UserManagerService.getInstance().getUserIds()) {
5371                final int packageCount = mPackages.size();
5372                for (int i = 0; i < packageCount; i++) {
5373                    PackageParser.Package pkg = mPackages.valueAt(i);
5374                    if (!(pkg.mExtras instanceof PackageSetting)) {
5375                        continue;
5376                    }
5377                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5378                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5379                }
5380            }
5381        }
5382    }
5383
5384    @Override
5385    public int getPermissionFlags(String permName, String packageName, int userId) {
5386        return mPermissionManager.getPermissionFlags(permName, packageName, getCallingUid(), userId);
5387    }
5388
5389    @Override
5390    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5391            int flagValues, int userId) {
5392        mPermissionManager.updatePermissionFlags(
5393                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5394                mPermissionCallback);
5395    }
5396
5397    /**
5398     * Update the permission flags for all packages and runtime permissions of a user in order
5399     * to allow device or profile owner to remove POLICY_FIXED.
5400     */
5401    @Override
5402    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5403        synchronized (mPackages) {
5404            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5405                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5406                    mPermissionCallback);
5407            if (changed) {
5408                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5409            }
5410        }
5411    }
5412
5413    @Override
5414    public boolean shouldShowRequestPermissionRationale(String permissionName,
5415            String packageName, int userId) {
5416        if (UserHandle.getCallingUserId() != userId) {
5417            mContext.enforceCallingPermission(
5418                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5419                    "canShowRequestPermissionRationale for user " + userId);
5420        }
5421
5422        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5423        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5424            return false;
5425        }
5426
5427        if (checkPermission(permissionName, packageName, userId)
5428                == PackageManager.PERMISSION_GRANTED) {
5429            return false;
5430        }
5431
5432        final int flags;
5433
5434        final long identity = Binder.clearCallingIdentity();
5435        try {
5436            flags = getPermissionFlags(permissionName,
5437                    packageName, userId);
5438        } finally {
5439            Binder.restoreCallingIdentity(identity);
5440        }
5441
5442        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5443                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5444                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5445
5446        if ((flags & fixedFlags) != 0) {
5447            return false;
5448        }
5449
5450        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5451    }
5452
5453    @Override
5454    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5455        mContext.enforceCallingOrSelfPermission(
5456                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5457                "addOnPermissionsChangeListener");
5458
5459        synchronized (mPackages) {
5460            mOnPermissionChangeListeners.addListenerLocked(listener);
5461        }
5462    }
5463
5464    @Override
5465    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5466        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5467            throw new SecurityException("Instant applications don't have access to this method");
5468        }
5469        synchronized (mPackages) {
5470            mOnPermissionChangeListeners.removeListenerLocked(listener);
5471        }
5472    }
5473
5474    @Override
5475    public boolean isProtectedBroadcast(String actionName) {
5476        // allow instant applications
5477        synchronized (mProtectedBroadcasts) {
5478            if (mProtectedBroadcasts.contains(actionName)) {
5479                return true;
5480            } else if (actionName != null) {
5481                // TODO: remove these terrible hacks
5482                if (actionName.startsWith("android.net.netmon.lingerExpired")
5483                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5484                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5485                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5486                    return true;
5487                }
5488            }
5489        }
5490        return false;
5491    }
5492
5493    @Override
5494    public int checkSignatures(String pkg1, String pkg2) {
5495        synchronized (mPackages) {
5496            final PackageParser.Package p1 = mPackages.get(pkg1);
5497            final PackageParser.Package p2 = mPackages.get(pkg2);
5498            if (p1 == null || p1.mExtras == null
5499                    || p2 == null || p2.mExtras == null) {
5500                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5501            }
5502            final int callingUid = Binder.getCallingUid();
5503            final int callingUserId = UserHandle.getUserId(callingUid);
5504            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5505            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5506            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5507                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5508                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5509            }
5510            return compareSignatures(p1.mSignatures, p2.mSignatures);
5511        }
5512    }
5513
5514    @Override
5515    public int checkUidSignatures(int uid1, int uid2) {
5516        final int callingUid = Binder.getCallingUid();
5517        final int callingUserId = UserHandle.getUserId(callingUid);
5518        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5519        // Map to base uids.
5520        uid1 = UserHandle.getAppId(uid1);
5521        uid2 = UserHandle.getAppId(uid2);
5522        // reader
5523        synchronized (mPackages) {
5524            Signature[] s1;
5525            Signature[] s2;
5526            Object obj = mSettings.getUserIdLPr(uid1);
5527            if (obj != null) {
5528                if (obj instanceof SharedUserSetting) {
5529                    if (isCallerInstantApp) {
5530                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5531                    }
5532                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5533                } else if (obj instanceof PackageSetting) {
5534                    final PackageSetting ps = (PackageSetting) obj;
5535                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5536                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5537                    }
5538                    s1 = ps.signatures.mSignatures;
5539                } else {
5540                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5541                }
5542            } else {
5543                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5544            }
5545            obj = mSettings.getUserIdLPr(uid2);
5546            if (obj != null) {
5547                if (obj instanceof SharedUserSetting) {
5548                    if (isCallerInstantApp) {
5549                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5550                    }
5551                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5552                } else if (obj instanceof PackageSetting) {
5553                    final PackageSetting ps = (PackageSetting) obj;
5554                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5555                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5556                    }
5557                    s2 = ps.signatures.mSignatures;
5558                } else {
5559                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5560                }
5561            } else {
5562                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5563            }
5564            return compareSignatures(s1, s2);
5565        }
5566    }
5567
5568    /**
5569     * This method should typically only be used when granting or revoking
5570     * permissions, since the app may immediately restart after this call.
5571     * <p>
5572     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5573     * guard your work against the app being relaunched.
5574     */
5575    private void killUid(int appId, int userId, String reason) {
5576        final long identity = Binder.clearCallingIdentity();
5577        try {
5578            IActivityManager am = ActivityManager.getService();
5579            if (am != null) {
5580                try {
5581                    am.killUid(appId, userId, reason);
5582                } catch (RemoteException e) {
5583                    /* ignore - same process */
5584                }
5585            }
5586        } finally {
5587            Binder.restoreCallingIdentity(identity);
5588        }
5589    }
5590
5591    /**
5592     * Compares two sets of signatures. Returns:
5593     * <br />
5594     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5595     * <br />
5596     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5597     * <br />
5598     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5599     * <br />
5600     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5601     * <br />
5602     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5603     */
5604    public static int compareSignatures(Signature[] s1, Signature[] s2) {
5605        if (s1 == null) {
5606            return s2 == null
5607                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5608                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5609        }
5610
5611        if (s2 == null) {
5612            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5613        }
5614
5615        if (s1.length != s2.length) {
5616            return PackageManager.SIGNATURE_NO_MATCH;
5617        }
5618
5619        // Since both signature sets are of size 1, we can compare without HashSets.
5620        if (s1.length == 1) {
5621            return s1[0].equals(s2[0]) ?
5622                    PackageManager.SIGNATURE_MATCH :
5623                    PackageManager.SIGNATURE_NO_MATCH;
5624        }
5625
5626        ArraySet<Signature> set1 = new ArraySet<Signature>();
5627        for (Signature sig : s1) {
5628            set1.add(sig);
5629        }
5630        ArraySet<Signature> set2 = new ArraySet<Signature>();
5631        for (Signature sig : s2) {
5632            set2.add(sig);
5633        }
5634        // Make sure s2 contains all signatures in s1.
5635        if (set1.equals(set2)) {
5636            return PackageManager.SIGNATURE_MATCH;
5637        }
5638        return PackageManager.SIGNATURE_NO_MATCH;
5639    }
5640
5641    /**
5642     * If the database version for this type of package (internal storage or
5643     * external storage) is less than the version where package signatures
5644     * were updated, return true.
5645     */
5646    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5647        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5648        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5649    }
5650
5651    /**
5652     * Used for backward compatibility to make sure any packages with
5653     * certificate chains get upgraded to the new style. {@code existingSigs}
5654     * will be in the old format (since they were stored on disk from before the
5655     * system upgrade) and {@code scannedSigs} will be in the newer format.
5656     */
5657    private int compareSignaturesCompat(PackageSignatures existingSigs,
5658            PackageParser.Package scannedPkg) {
5659        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5660            return PackageManager.SIGNATURE_NO_MATCH;
5661        }
5662
5663        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5664        for (Signature sig : existingSigs.mSignatures) {
5665            existingSet.add(sig);
5666        }
5667        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5668        for (Signature sig : scannedPkg.mSignatures) {
5669            try {
5670                Signature[] chainSignatures = sig.getChainSignatures();
5671                for (Signature chainSig : chainSignatures) {
5672                    scannedCompatSet.add(chainSig);
5673                }
5674            } catch (CertificateEncodingException e) {
5675                scannedCompatSet.add(sig);
5676            }
5677        }
5678        /*
5679         * Make sure the expanded scanned set contains all signatures in the
5680         * existing one.
5681         */
5682        if (scannedCompatSet.equals(existingSet)) {
5683            // Migrate the old signatures to the new scheme.
5684            existingSigs.assignSignatures(scannedPkg.mSignatures);
5685            // The new KeySets will be re-added later in the scanning process.
5686            synchronized (mPackages) {
5687                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5688            }
5689            return PackageManager.SIGNATURE_MATCH;
5690        }
5691        return PackageManager.SIGNATURE_NO_MATCH;
5692    }
5693
5694    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5695        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5696        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5697    }
5698
5699    private int compareSignaturesRecover(PackageSignatures existingSigs,
5700            PackageParser.Package scannedPkg) {
5701        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5702            return PackageManager.SIGNATURE_NO_MATCH;
5703        }
5704
5705        String msg = null;
5706        try {
5707            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5708                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5709                        + scannedPkg.packageName);
5710                return PackageManager.SIGNATURE_MATCH;
5711            }
5712        } catch (CertificateException e) {
5713            msg = e.getMessage();
5714        }
5715
5716        logCriticalInfo(Log.INFO,
5717                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5718        return PackageManager.SIGNATURE_NO_MATCH;
5719    }
5720
5721    @Override
5722    public List<String> getAllPackages() {
5723        final int callingUid = Binder.getCallingUid();
5724        final int callingUserId = UserHandle.getUserId(callingUid);
5725        synchronized (mPackages) {
5726            if (canViewInstantApps(callingUid, callingUserId)) {
5727                return new ArrayList<String>(mPackages.keySet());
5728            }
5729            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5730            final List<String> result = new ArrayList<>();
5731            if (instantAppPkgName != null) {
5732                // caller is an instant application; filter unexposed applications
5733                for (PackageParser.Package pkg : mPackages.values()) {
5734                    if (!pkg.visibleToInstantApps) {
5735                        continue;
5736                    }
5737                    result.add(pkg.packageName);
5738                }
5739            } else {
5740                // caller is a normal application; filter instant applications
5741                for (PackageParser.Package pkg : mPackages.values()) {
5742                    final PackageSetting ps =
5743                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5744                    if (ps != null
5745                            && ps.getInstantApp(callingUserId)
5746                            && !mInstantAppRegistry.isInstantAccessGranted(
5747                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5748                        continue;
5749                    }
5750                    result.add(pkg.packageName);
5751                }
5752            }
5753            return result;
5754        }
5755    }
5756
5757    @Override
5758    public String[] getPackagesForUid(int uid) {
5759        final int callingUid = Binder.getCallingUid();
5760        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5761        final int userId = UserHandle.getUserId(uid);
5762        uid = UserHandle.getAppId(uid);
5763        // reader
5764        synchronized (mPackages) {
5765            Object obj = mSettings.getUserIdLPr(uid);
5766            if (obj instanceof SharedUserSetting) {
5767                if (isCallerInstantApp) {
5768                    return null;
5769                }
5770                final SharedUserSetting sus = (SharedUserSetting) obj;
5771                final int N = sus.packages.size();
5772                String[] res = new String[N];
5773                final Iterator<PackageSetting> it = sus.packages.iterator();
5774                int i = 0;
5775                while (it.hasNext()) {
5776                    PackageSetting ps = it.next();
5777                    if (ps.getInstalled(userId)) {
5778                        res[i++] = ps.name;
5779                    } else {
5780                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5781                    }
5782                }
5783                return res;
5784            } else if (obj instanceof PackageSetting) {
5785                final PackageSetting ps = (PackageSetting) obj;
5786                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5787                    return new String[]{ps.name};
5788                }
5789            }
5790        }
5791        return null;
5792    }
5793
5794    @Override
5795    public String getNameForUid(int uid) {
5796        final int callingUid = Binder.getCallingUid();
5797        if (getInstantAppPackageName(callingUid) != null) {
5798            return null;
5799        }
5800        synchronized (mPackages) {
5801            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5802            if (obj instanceof SharedUserSetting) {
5803                final SharedUserSetting sus = (SharedUserSetting) obj;
5804                return sus.name + ":" + sus.userId;
5805            } else if (obj instanceof PackageSetting) {
5806                final PackageSetting ps = (PackageSetting) obj;
5807                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5808                    return null;
5809                }
5810                return ps.name;
5811            }
5812            return null;
5813        }
5814    }
5815
5816    @Override
5817    public String[] getNamesForUids(int[] uids) {
5818        if (uids == null || uids.length == 0) {
5819            return null;
5820        }
5821        final int callingUid = Binder.getCallingUid();
5822        if (getInstantAppPackageName(callingUid) != null) {
5823            return null;
5824        }
5825        final String[] names = new String[uids.length];
5826        synchronized (mPackages) {
5827            for (int i = uids.length - 1; i >= 0; i--) {
5828                final int uid = uids[i];
5829                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5830                if (obj instanceof SharedUserSetting) {
5831                    final SharedUserSetting sus = (SharedUserSetting) obj;
5832                    names[i] = "shared:" + sus.name;
5833                } else if (obj instanceof PackageSetting) {
5834                    final PackageSetting ps = (PackageSetting) obj;
5835                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5836                        names[i] = null;
5837                    } else {
5838                        names[i] = ps.name;
5839                    }
5840                } else {
5841                    names[i] = null;
5842                }
5843            }
5844        }
5845        return names;
5846    }
5847
5848    @Override
5849    public int getUidForSharedUser(String sharedUserName) {
5850        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5851            return -1;
5852        }
5853        if (sharedUserName == null) {
5854            return -1;
5855        }
5856        // reader
5857        synchronized (mPackages) {
5858            SharedUserSetting suid;
5859            try {
5860                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5861                if (suid != null) {
5862                    return suid.userId;
5863                }
5864            } catch (PackageManagerException ignore) {
5865                // can't happen, but, still need to catch it
5866            }
5867            return -1;
5868        }
5869    }
5870
5871    @Override
5872    public int getFlagsForUid(int uid) {
5873        final int callingUid = Binder.getCallingUid();
5874        if (getInstantAppPackageName(callingUid) != null) {
5875            return 0;
5876        }
5877        synchronized (mPackages) {
5878            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5879            if (obj instanceof SharedUserSetting) {
5880                final SharedUserSetting sus = (SharedUserSetting) obj;
5881                return sus.pkgFlags;
5882            } else if (obj instanceof PackageSetting) {
5883                final PackageSetting ps = (PackageSetting) obj;
5884                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5885                    return 0;
5886                }
5887                return ps.pkgFlags;
5888            }
5889        }
5890        return 0;
5891    }
5892
5893    @Override
5894    public int getPrivateFlagsForUid(int uid) {
5895        final int callingUid = Binder.getCallingUid();
5896        if (getInstantAppPackageName(callingUid) != null) {
5897            return 0;
5898        }
5899        synchronized (mPackages) {
5900            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5901            if (obj instanceof SharedUserSetting) {
5902                final SharedUserSetting sus = (SharedUserSetting) obj;
5903                return sus.pkgPrivateFlags;
5904            } else if (obj instanceof PackageSetting) {
5905                final PackageSetting ps = (PackageSetting) obj;
5906                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5907                    return 0;
5908                }
5909                return ps.pkgPrivateFlags;
5910            }
5911        }
5912        return 0;
5913    }
5914
5915    @Override
5916    public boolean isUidPrivileged(int uid) {
5917        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5918            return false;
5919        }
5920        uid = UserHandle.getAppId(uid);
5921        // reader
5922        synchronized (mPackages) {
5923            Object obj = mSettings.getUserIdLPr(uid);
5924            if (obj instanceof SharedUserSetting) {
5925                final SharedUserSetting sus = (SharedUserSetting) obj;
5926                final Iterator<PackageSetting> it = sus.packages.iterator();
5927                while (it.hasNext()) {
5928                    if (it.next().isPrivileged()) {
5929                        return true;
5930                    }
5931                }
5932            } else if (obj instanceof PackageSetting) {
5933                final PackageSetting ps = (PackageSetting) obj;
5934                return ps.isPrivileged();
5935            }
5936        }
5937        return false;
5938    }
5939
5940    @Override
5941    public String[] getAppOpPermissionPackages(String permName) {
5942        return mPermissionManager.getAppOpPermissionPackages(permName);
5943    }
5944
5945    @Override
5946    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5947            int flags, int userId) {
5948        return resolveIntentInternal(
5949                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5950    }
5951
5952    /**
5953     * Normally instant apps can only be resolved when they're visible to the caller.
5954     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5955     * since we need to allow the system to start any installed application.
5956     */
5957    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5958            int flags, int userId, boolean resolveForStart) {
5959        try {
5960            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5961
5962            if (!sUserManager.exists(userId)) return null;
5963            final int callingUid = Binder.getCallingUid();
5964            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5965            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5966                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5967
5968            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5969            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5970                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5971            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5972
5973            final ResolveInfo bestChoice =
5974                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5975            return bestChoice;
5976        } finally {
5977            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5978        }
5979    }
5980
5981    @Override
5982    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5983        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5984            throw new SecurityException(
5985                    "findPersistentPreferredActivity can only be run by the system");
5986        }
5987        if (!sUserManager.exists(userId)) {
5988            return null;
5989        }
5990        final int callingUid = Binder.getCallingUid();
5991        intent = updateIntentForResolve(intent);
5992        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5993        final int flags = updateFlagsForResolve(
5994                0, userId, intent, callingUid, false /*includeInstantApps*/);
5995        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5996                userId);
5997        synchronized (mPackages) {
5998            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5999                    userId);
6000        }
6001    }
6002
6003    @Override
6004    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6005            IntentFilter filter, int match, ComponentName activity) {
6006        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6007            return;
6008        }
6009        final int userId = UserHandle.getCallingUserId();
6010        if (DEBUG_PREFERRED) {
6011            Log.v(TAG, "setLastChosenActivity intent=" + intent
6012                + " resolvedType=" + resolvedType
6013                + " flags=" + flags
6014                + " filter=" + filter
6015                + " match=" + match
6016                + " activity=" + activity);
6017            filter.dump(new PrintStreamPrinter(System.out), "    ");
6018        }
6019        intent.setComponent(null);
6020        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6021                userId);
6022        // Find any earlier preferred or last chosen entries and nuke them
6023        findPreferredActivity(intent, resolvedType,
6024                flags, query, 0, false, true, false, userId);
6025        // Add the new activity as the last chosen for this filter
6026        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6027                "Setting last chosen");
6028    }
6029
6030    @Override
6031    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6032        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6033            return null;
6034        }
6035        final int userId = UserHandle.getCallingUserId();
6036        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6037        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6038                userId);
6039        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6040                false, false, false, userId);
6041    }
6042
6043    /**
6044     * Returns whether or not instant apps have been disabled remotely.
6045     */
6046    private boolean isEphemeralDisabled() {
6047        return mEphemeralAppsDisabled;
6048    }
6049
6050    private boolean isInstantAppAllowed(
6051            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6052            boolean skipPackageCheck) {
6053        if (mInstantAppResolverConnection == null) {
6054            return false;
6055        }
6056        if (mInstantAppInstallerActivity == null) {
6057            return false;
6058        }
6059        if (intent.getComponent() != null) {
6060            return false;
6061        }
6062        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6063            return false;
6064        }
6065        if (!skipPackageCheck && intent.getPackage() != null) {
6066            return false;
6067        }
6068        final boolean isWebUri = hasWebURI(intent);
6069        if (!isWebUri || intent.getData().getHost() == null) {
6070            return false;
6071        }
6072        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6073        // Or if there's already an ephemeral app installed that handles the action
6074        synchronized (mPackages) {
6075            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6076            for (int n = 0; n < count; n++) {
6077                final ResolveInfo info = resolvedActivities.get(n);
6078                final String packageName = info.activityInfo.packageName;
6079                final PackageSetting ps = mSettings.mPackages.get(packageName);
6080                if (ps != null) {
6081                    // only check domain verification status if the app is not a browser
6082                    if (!info.handleAllWebDataURI) {
6083                        // Try to get the status from User settings first
6084                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6085                        final int status = (int) (packedStatus >> 32);
6086                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6087                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6088                            if (DEBUG_EPHEMERAL) {
6089                                Slog.v(TAG, "DENY instant app;"
6090                                    + " pkg: " + packageName + ", status: " + status);
6091                            }
6092                            return false;
6093                        }
6094                    }
6095                    if (ps.getInstantApp(userId)) {
6096                        if (DEBUG_EPHEMERAL) {
6097                            Slog.v(TAG, "DENY instant app installed;"
6098                                    + " pkg: " + packageName);
6099                        }
6100                        return false;
6101                    }
6102                }
6103            }
6104        }
6105        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6106        return true;
6107    }
6108
6109    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6110            Intent origIntent, String resolvedType, String callingPackage,
6111            Bundle verificationBundle, int userId) {
6112        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6113                new InstantAppRequest(responseObj, origIntent, resolvedType,
6114                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6115        mHandler.sendMessage(msg);
6116    }
6117
6118    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6119            int flags, List<ResolveInfo> query, int userId) {
6120        if (query != null) {
6121            final int N = query.size();
6122            if (N == 1) {
6123                return query.get(0);
6124            } else if (N > 1) {
6125                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6126                // If there is more than one activity with the same priority,
6127                // then let the user decide between them.
6128                ResolveInfo r0 = query.get(0);
6129                ResolveInfo r1 = query.get(1);
6130                if (DEBUG_INTENT_MATCHING || debug) {
6131                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6132                            + r1.activityInfo.name + "=" + r1.priority);
6133                }
6134                // If the first activity has a higher priority, or a different
6135                // default, then it is always desirable to pick it.
6136                if (r0.priority != r1.priority
6137                        || r0.preferredOrder != r1.preferredOrder
6138                        || r0.isDefault != r1.isDefault) {
6139                    return query.get(0);
6140                }
6141                // If we have saved a preference for a preferred activity for
6142                // this Intent, use that.
6143                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6144                        flags, query, r0.priority, true, false, debug, userId);
6145                if (ri != null) {
6146                    return ri;
6147                }
6148                // If we have an ephemeral app, use it
6149                for (int i = 0; i < N; i++) {
6150                    ri = query.get(i);
6151                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6152                        final String packageName = ri.activityInfo.packageName;
6153                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6154                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6155                        final int status = (int)(packedStatus >> 32);
6156                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6157                            return ri;
6158                        }
6159                    }
6160                }
6161                ri = new ResolveInfo(mResolveInfo);
6162                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6163                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6164                // If all of the options come from the same package, show the application's
6165                // label and icon instead of the generic resolver's.
6166                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6167                // and then throw away the ResolveInfo itself, meaning that the caller loses
6168                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6169                // a fallback for this case; we only set the target package's resources on
6170                // the ResolveInfo, not the ActivityInfo.
6171                final String intentPackage = intent.getPackage();
6172                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6173                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6174                    ri.resolvePackageName = intentPackage;
6175                    if (userNeedsBadging(userId)) {
6176                        ri.noResourceId = true;
6177                    } else {
6178                        ri.icon = appi.icon;
6179                    }
6180                    ri.iconResourceId = appi.icon;
6181                    ri.labelRes = appi.labelRes;
6182                }
6183                ri.activityInfo.applicationInfo = new ApplicationInfo(
6184                        ri.activityInfo.applicationInfo);
6185                if (userId != 0) {
6186                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6187                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6188                }
6189                // Make sure that the resolver is displayable in car mode
6190                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6191                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6192                return ri;
6193            }
6194        }
6195        return null;
6196    }
6197
6198    /**
6199     * Return true if the given list is not empty and all of its contents have
6200     * an activityInfo with the given package name.
6201     */
6202    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6203        if (ArrayUtils.isEmpty(list)) {
6204            return false;
6205        }
6206        for (int i = 0, N = list.size(); i < N; i++) {
6207            final ResolveInfo ri = list.get(i);
6208            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6209            if (ai == null || !packageName.equals(ai.packageName)) {
6210                return false;
6211            }
6212        }
6213        return true;
6214    }
6215
6216    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6217            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6218        final int N = query.size();
6219        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6220                .get(userId);
6221        // Get the list of persistent preferred activities that handle the intent
6222        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6223        List<PersistentPreferredActivity> pprefs = ppir != null
6224                ? ppir.queryIntent(intent, resolvedType,
6225                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6226                        userId)
6227                : null;
6228        if (pprefs != null && pprefs.size() > 0) {
6229            final int M = pprefs.size();
6230            for (int i=0; i<M; i++) {
6231                final PersistentPreferredActivity ppa = pprefs.get(i);
6232                if (DEBUG_PREFERRED || debug) {
6233                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6234                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6235                            + "\n  component=" + ppa.mComponent);
6236                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6237                }
6238                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6239                        flags | MATCH_DISABLED_COMPONENTS, userId);
6240                if (DEBUG_PREFERRED || debug) {
6241                    Slog.v(TAG, "Found persistent preferred activity:");
6242                    if (ai != null) {
6243                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6244                    } else {
6245                        Slog.v(TAG, "  null");
6246                    }
6247                }
6248                if (ai == null) {
6249                    // This previously registered persistent preferred activity
6250                    // component is no longer known. Ignore it and do NOT remove it.
6251                    continue;
6252                }
6253                for (int j=0; j<N; j++) {
6254                    final ResolveInfo ri = query.get(j);
6255                    if (!ri.activityInfo.applicationInfo.packageName
6256                            .equals(ai.applicationInfo.packageName)) {
6257                        continue;
6258                    }
6259                    if (!ri.activityInfo.name.equals(ai.name)) {
6260                        continue;
6261                    }
6262                    //  Found a persistent preference that can handle the intent.
6263                    if (DEBUG_PREFERRED || debug) {
6264                        Slog.v(TAG, "Returning persistent preferred activity: " +
6265                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6266                    }
6267                    return ri;
6268                }
6269            }
6270        }
6271        return null;
6272    }
6273
6274    // TODO: handle preferred activities missing while user has amnesia
6275    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6276            List<ResolveInfo> query, int priority, boolean always,
6277            boolean removeMatches, boolean debug, int userId) {
6278        if (!sUserManager.exists(userId)) return null;
6279        final int callingUid = Binder.getCallingUid();
6280        flags = updateFlagsForResolve(
6281                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6282        intent = updateIntentForResolve(intent);
6283        // writer
6284        synchronized (mPackages) {
6285            // Try to find a matching persistent preferred activity.
6286            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6287                    debug, userId);
6288
6289            // If a persistent preferred activity matched, use it.
6290            if (pri != null) {
6291                return pri;
6292            }
6293
6294            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6295            // Get the list of preferred activities that handle the intent
6296            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6297            List<PreferredActivity> prefs = pir != null
6298                    ? pir.queryIntent(intent, resolvedType,
6299                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6300                            userId)
6301                    : null;
6302            if (prefs != null && prefs.size() > 0) {
6303                boolean changed = false;
6304                try {
6305                    // First figure out how good the original match set is.
6306                    // We will only allow preferred activities that came
6307                    // from the same match quality.
6308                    int match = 0;
6309
6310                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6311
6312                    final int N = query.size();
6313                    for (int j=0; j<N; j++) {
6314                        final ResolveInfo ri = query.get(j);
6315                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6316                                + ": 0x" + Integer.toHexString(match));
6317                        if (ri.match > match) {
6318                            match = ri.match;
6319                        }
6320                    }
6321
6322                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6323                            + Integer.toHexString(match));
6324
6325                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6326                    final int M = prefs.size();
6327                    for (int i=0; i<M; i++) {
6328                        final PreferredActivity pa = prefs.get(i);
6329                        if (DEBUG_PREFERRED || debug) {
6330                            Slog.v(TAG, "Checking PreferredActivity ds="
6331                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6332                                    + "\n  component=" + pa.mPref.mComponent);
6333                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6334                        }
6335                        if (pa.mPref.mMatch != match) {
6336                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6337                                    + Integer.toHexString(pa.mPref.mMatch));
6338                            continue;
6339                        }
6340                        // If it's not an "always" type preferred activity and that's what we're
6341                        // looking for, skip it.
6342                        if (always && !pa.mPref.mAlways) {
6343                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6344                            continue;
6345                        }
6346                        final ActivityInfo ai = getActivityInfo(
6347                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6348                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6349                                userId);
6350                        if (DEBUG_PREFERRED || debug) {
6351                            Slog.v(TAG, "Found preferred activity:");
6352                            if (ai != null) {
6353                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6354                            } else {
6355                                Slog.v(TAG, "  null");
6356                            }
6357                        }
6358                        if (ai == null) {
6359                            // This previously registered preferred activity
6360                            // component is no longer known.  Most likely an update
6361                            // to the app was installed and in the new version this
6362                            // component no longer exists.  Clean it up by removing
6363                            // it from the preferred activities list, and skip it.
6364                            Slog.w(TAG, "Removing dangling preferred activity: "
6365                                    + pa.mPref.mComponent);
6366                            pir.removeFilter(pa);
6367                            changed = true;
6368                            continue;
6369                        }
6370                        for (int j=0; j<N; j++) {
6371                            final ResolveInfo ri = query.get(j);
6372                            if (!ri.activityInfo.applicationInfo.packageName
6373                                    .equals(ai.applicationInfo.packageName)) {
6374                                continue;
6375                            }
6376                            if (!ri.activityInfo.name.equals(ai.name)) {
6377                                continue;
6378                            }
6379
6380                            if (removeMatches) {
6381                                pir.removeFilter(pa);
6382                                changed = true;
6383                                if (DEBUG_PREFERRED) {
6384                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6385                                }
6386                                break;
6387                            }
6388
6389                            // Okay we found a previously set preferred or last chosen app.
6390                            // If the result set is different from when this
6391                            // was created, and is not a subset of the preferred set, we need to
6392                            // clear it and re-ask the user their preference, if we're looking for
6393                            // an "always" type entry.
6394                            if (always && !pa.mPref.sameSet(query)) {
6395                                if (pa.mPref.isSuperset(query)) {
6396                                    // some components of the set are no longer present in
6397                                    // the query, but the preferred activity can still be reused
6398                                    if (DEBUG_PREFERRED) {
6399                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6400                                                + " still valid as only non-preferred components"
6401                                                + " were removed for " + intent + " type "
6402                                                + resolvedType);
6403                                    }
6404                                    // remove obsolete components and re-add the up-to-date filter
6405                                    PreferredActivity freshPa = new PreferredActivity(pa,
6406                                            pa.mPref.mMatch,
6407                                            pa.mPref.discardObsoleteComponents(query),
6408                                            pa.mPref.mComponent,
6409                                            pa.mPref.mAlways);
6410                                    pir.removeFilter(pa);
6411                                    pir.addFilter(freshPa);
6412                                    changed = true;
6413                                } else {
6414                                    Slog.i(TAG,
6415                                            "Result set changed, dropping preferred activity for "
6416                                                    + intent + " type " + resolvedType);
6417                                    if (DEBUG_PREFERRED) {
6418                                        Slog.v(TAG, "Removing preferred activity since set changed "
6419                                                + pa.mPref.mComponent);
6420                                    }
6421                                    pir.removeFilter(pa);
6422                                    // Re-add the filter as a "last chosen" entry (!always)
6423                                    PreferredActivity lastChosen = new PreferredActivity(
6424                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6425                                    pir.addFilter(lastChosen);
6426                                    changed = true;
6427                                    return null;
6428                                }
6429                            }
6430
6431                            // Yay! Either the set matched or we're looking for the last chosen
6432                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6433                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6434                            return ri;
6435                        }
6436                    }
6437                } finally {
6438                    if (changed) {
6439                        if (DEBUG_PREFERRED) {
6440                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6441                        }
6442                        scheduleWritePackageRestrictionsLocked(userId);
6443                    }
6444                }
6445            }
6446        }
6447        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6448        return null;
6449    }
6450
6451    /*
6452     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6453     */
6454    @Override
6455    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6456            int targetUserId) {
6457        mContext.enforceCallingOrSelfPermission(
6458                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6459        List<CrossProfileIntentFilter> matches =
6460                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6461        if (matches != null) {
6462            int size = matches.size();
6463            for (int i = 0; i < size; i++) {
6464                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6465            }
6466        }
6467        if (hasWebURI(intent)) {
6468            // cross-profile app linking works only towards the parent.
6469            final int callingUid = Binder.getCallingUid();
6470            final UserInfo parent = getProfileParent(sourceUserId);
6471            synchronized(mPackages) {
6472                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6473                        false /*includeInstantApps*/);
6474                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6475                        intent, resolvedType, flags, sourceUserId, parent.id);
6476                return xpDomainInfo != null;
6477            }
6478        }
6479        return false;
6480    }
6481
6482    private UserInfo getProfileParent(int userId) {
6483        final long identity = Binder.clearCallingIdentity();
6484        try {
6485            return sUserManager.getProfileParent(userId);
6486        } finally {
6487            Binder.restoreCallingIdentity(identity);
6488        }
6489    }
6490
6491    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6492            String resolvedType, int userId) {
6493        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6494        if (resolver != null) {
6495            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6496        }
6497        return null;
6498    }
6499
6500    @Override
6501    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6502            String resolvedType, int flags, int userId) {
6503        try {
6504            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6505
6506            return new ParceledListSlice<>(
6507                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6508        } finally {
6509            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6510        }
6511    }
6512
6513    /**
6514     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6515     * instant, returns {@code null}.
6516     */
6517    private String getInstantAppPackageName(int callingUid) {
6518        synchronized (mPackages) {
6519            // If the caller is an isolated app use the owner's uid for the lookup.
6520            if (Process.isIsolated(callingUid)) {
6521                callingUid = mIsolatedOwners.get(callingUid);
6522            }
6523            final int appId = UserHandle.getAppId(callingUid);
6524            final Object obj = mSettings.getUserIdLPr(appId);
6525            if (obj instanceof PackageSetting) {
6526                final PackageSetting ps = (PackageSetting) obj;
6527                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6528                return isInstantApp ? ps.pkg.packageName : null;
6529            }
6530        }
6531        return null;
6532    }
6533
6534    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6535            String resolvedType, int flags, int userId) {
6536        return queryIntentActivitiesInternal(
6537                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6538                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6539    }
6540
6541    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6542            String resolvedType, int flags, int filterCallingUid, int userId,
6543            boolean resolveForStart, boolean allowDynamicSplits) {
6544        if (!sUserManager.exists(userId)) return Collections.emptyList();
6545        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6546        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6547                false /* requireFullPermission */, false /* checkShell */,
6548                "query intent activities");
6549        final String pkgName = intent.getPackage();
6550        ComponentName comp = intent.getComponent();
6551        if (comp == null) {
6552            if (intent.getSelector() != null) {
6553                intent = intent.getSelector();
6554                comp = intent.getComponent();
6555            }
6556        }
6557
6558        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6559                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6560        if (comp != null) {
6561            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6562            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6563            if (ai != null) {
6564                // When specifying an explicit component, we prevent the activity from being
6565                // used when either 1) the calling package is normal and the activity is within
6566                // an ephemeral application or 2) the calling package is ephemeral and the
6567                // activity is not visible to ephemeral applications.
6568                final boolean matchInstantApp =
6569                        (flags & PackageManager.MATCH_INSTANT) != 0;
6570                final boolean matchVisibleToInstantAppOnly =
6571                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6572                final boolean matchExplicitlyVisibleOnly =
6573                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6574                final boolean isCallerInstantApp =
6575                        instantAppPkgName != null;
6576                final boolean isTargetSameInstantApp =
6577                        comp.getPackageName().equals(instantAppPkgName);
6578                final boolean isTargetInstantApp =
6579                        (ai.applicationInfo.privateFlags
6580                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6581                final boolean isTargetVisibleToInstantApp =
6582                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6583                final boolean isTargetExplicitlyVisibleToInstantApp =
6584                        isTargetVisibleToInstantApp
6585                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6586                final boolean isTargetHiddenFromInstantApp =
6587                        !isTargetVisibleToInstantApp
6588                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6589                final boolean blockResolution =
6590                        !isTargetSameInstantApp
6591                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6592                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6593                                        && isTargetHiddenFromInstantApp));
6594                if (!blockResolution) {
6595                    final ResolveInfo ri = new ResolveInfo();
6596                    ri.activityInfo = ai;
6597                    list.add(ri);
6598                }
6599            }
6600            return applyPostResolutionFilter(
6601                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6602        }
6603
6604        // reader
6605        boolean sortResult = false;
6606        boolean addEphemeral = false;
6607        List<ResolveInfo> result;
6608        final boolean ephemeralDisabled = isEphemeralDisabled();
6609        synchronized (mPackages) {
6610            if (pkgName == null) {
6611                List<CrossProfileIntentFilter> matchingFilters =
6612                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6613                // Check for results that need to skip the current profile.
6614                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6615                        resolvedType, flags, userId);
6616                if (xpResolveInfo != null) {
6617                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6618                    xpResult.add(xpResolveInfo);
6619                    return applyPostResolutionFilter(
6620                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6621                            allowDynamicSplits, filterCallingUid, userId);
6622                }
6623
6624                // Check for results in the current profile.
6625                result = filterIfNotSystemUser(mActivities.queryIntent(
6626                        intent, resolvedType, flags, userId), userId);
6627                addEphemeral = !ephemeralDisabled
6628                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6629                // Check for cross profile results.
6630                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6631                xpResolveInfo = queryCrossProfileIntents(
6632                        matchingFilters, intent, resolvedType, flags, userId,
6633                        hasNonNegativePriorityResult);
6634                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6635                    boolean isVisibleToUser = filterIfNotSystemUser(
6636                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6637                    if (isVisibleToUser) {
6638                        result.add(xpResolveInfo);
6639                        sortResult = true;
6640                    }
6641                }
6642                if (hasWebURI(intent)) {
6643                    CrossProfileDomainInfo xpDomainInfo = null;
6644                    final UserInfo parent = getProfileParent(userId);
6645                    if (parent != null) {
6646                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6647                                flags, userId, parent.id);
6648                    }
6649                    if (xpDomainInfo != null) {
6650                        if (xpResolveInfo != null) {
6651                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6652                            // in the result.
6653                            result.remove(xpResolveInfo);
6654                        }
6655                        if (result.size() == 0 && !addEphemeral) {
6656                            // No result in current profile, but found candidate in parent user.
6657                            // And we are not going to add emphemeral app, so we can return the
6658                            // result straight away.
6659                            result.add(xpDomainInfo.resolveInfo);
6660                            return applyPostResolutionFilter(result, instantAppPkgName,
6661                                    allowDynamicSplits, filterCallingUid, userId);
6662                        }
6663                    } else if (result.size() <= 1 && !addEphemeral) {
6664                        // No result in parent user and <= 1 result in current profile, and we
6665                        // are not going to add emphemeral app, so we can return the result without
6666                        // further processing.
6667                        return applyPostResolutionFilter(result, instantAppPkgName,
6668                                allowDynamicSplits, filterCallingUid, userId);
6669                    }
6670                    // We have more than one candidate (combining results from current and parent
6671                    // profile), so we need filtering and sorting.
6672                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6673                            intent, flags, result, xpDomainInfo, userId);
6674                    sortResult = true;
6675                }
6676            } else {
6677                final PackageParser.Package pkg = mPackages.get(pkgName);
6678                result = null;
6679                if (pkg != null) {
6680                    result = filterIfNotSystemUser(
6681                            mActivities.queryIntentForPackage(
6682                                    intent, resolvedType, flags, pkg.activities, userId),
6683                            userId);
6684                }
6685                if (result == null || result.size() == 0) {
6686                    // the caller wants to resolve for a particular package; however, there
6687                    // were no installed results, so, try to find an ephemeral result
6688                    addEphemeral = !ephemeralDisabled
6689                            && isInstantAppAllowed(
6690                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6691                    if (result == null) {
6692                        result = new ArrayList<>();
6693                    }
6694                }
6695            }
6696        }
6697        if (addEphemeral) {
6698            result = maybeAddInstantAppInstaller(
6699                    result, intent, resolvedType, flags, userId, resolveForStart);
6700        }
6701        if (sortResult) {
6702            Collections.sort(result, mResolvePrioritySorter);
6703        }
6704        return applyPostResolutionFilter(
6705                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
6706    }
6707
6708    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6709            String resolvedType, int flags, int userId, boolean resolveForStart) {
6710        // first, check to see if we've got an instant app already installed
6711        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6712        ResolveInfo localInstantApp = null;
6713        boolean blockResolution = false;
6714        if (!alreadyResolvedLocally) {
6715            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6716                    flags
6717                        | PackageManager.GET_RESOLVED_FILTER
6718                        | PackageManager.MATCH_INSTANT
6719                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6720                    userId);
6721            for (int i = instantApps.size() - 1; i >= 0; --i) {
6722                final ResolveInfo info = instantApps.get(i);
6723                final String packageName = info.activityInfo.packageName;
6724                final PackageSetting ps = mSettings.mPackages.get(packageName);
6725                if (ps.getInstantApp(userId)) {
6726                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6727                    final int status = (int)(packedStatus >> 32);
6728                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6729                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6730                        // there's a local instant application installed, but, the user has
6731                        // chosen to never use it; skip resolution and don't acknowledge
6732                        // an instant application is even available
6733                        if (DEBUG_EPHEMERAL) {
6734                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6735                        }
6736                        blockResolution = true;
6737                        break;
6738                    } else {
6739                        // we have a locally installed instant application; skip resolution
6740                        // but acknowledge there's an instant application available
6741                        if (DEBUG_EPHEMERAL) {
6742                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6743                        }
6744                        localInstantApp = info;
6745                        break;
6746                    }
6747                }
6748            }
6749        }
6750        // no app installed, let's see if one's available
6751        AuxiliaryResolveInfo auxiliaryResponse = null;
6752        if (!blockResolution) {
6753            if (localInstantApp == null) {
6754                // we don't have an instant app locally, resolve externally
6755                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6756                final InstantAppRequest requestObject = new InstantAppRequest(
6757                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6758                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6759                        resolveForStart);
6760                auxiliaryResponse =
6761                        InstantAppResolver.doInstantAppResolutionPhaseOne(
6762                                mContext, mInstantAppResolverConnection, requestObject);
6763                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6764            } else {
6765                // we have an instant application locally, but, we can't admit that since
6766                // callers shouldn't be able to determine prior browsing. create a dummy
6767                // auxiliary response so the downstream code behaves as if there's an
6768                // instant application available externally. when it comes time to start
6769                // the instant application, we'll do the right thing.
6770                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6771                auxiliaryResponse = new AuxiliaryResolveInfo(
6772                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
6773                        ai.versionCode, null /*failureIntent*/);
6774            }
6775        }
6776        if (auxiliaryResponse != null) {
6777            if (DEBUG_EPHEMERAL) {
6778                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6779            }
6780            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6781            final PackageSetting ps =
6782                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6783            if (ps != null) {
6784                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6785                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6786                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6787                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6788                // make sure this resolver is the default
6789                ephemeralInstaller.isDefault = true;
6790                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6791                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6792                // add a non-generic filter
6793                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6794                ephemeralInstaller.filter.addDataPath(
6795                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6796                ephemeralInstaller.isInstantAppAvailable = true;
6797                result.add(ephemeralInstaller);
6798            }
6799        }
6800        return result;
6801    }
6802
6803    private static class CrossProfileDomainInfo {
6804        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6805        ResolveInfo resolveInfo;
6806        /* Best domain verification status of the activities found in the other profile */
6807        int bestDomainVerificationStatus;
6808    }
6809
6810    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6811            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6812        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6813                sourceUserId)) {
6814            return null;
6815        }
6816        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6817                resolvedType, flags, parentUserId);
6818
6819        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6820            return null;
6821        }
6822        CrossProfileDomainInfo result = null;
6823        int size = resultTargetUser.size();
6824        for (int i = 0; i < size; i++) {
6825            ResolveInfo riTargetUser = resultTargetUser.get(i);
6826            // Intent filter verification is only for filters that specify a host. So don't return
6827            // those that handle all web uris.
6828            if (riTargetUser.handleAllWebDataURI) {
6829                continue;
6830            }
6831            String packageName = riTargetUser.activityInfo.packageName;
6832            PackageSetting ps = mSettings.mPackages.get(packageName);
6833            if (ps == null) {
6834                continue;
6835            }
6836            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6837            int status = (int)(verificationState >> 32);
6838            if (result == null) {
6839                result = new CrossProfileDomainInfo();
6840                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6841                        sourceUserId, parentUserId);
6842                result.bestDomainVerificationStatus = status;
6843            } else {
6844                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6845                        result.bestDomainVerificationStatus);
6846            }
6847        }
6848        // Don't consider matches with status NEVER across profiles.
6849        if (result != null && result.bestDomainVerificationStatus
6850                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6851            return null;
6852        }
6853        return result;
6854    }
6855
6856    /**
6857     * Verification statuses are ordered from the worse to the best, except for
6858     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6859     */
6860    private int bestDomainVerificationStatus(int status1, int status2) {
6861        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6862            return status2;
6863        }
6864        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6865            return status1;
6866        }
6867        return (int) MathUtils.max(status1, status2);
6868    }
6869
6870    private boolean isUserEnabled(int userId) {
6871        long callingId = Binder.clearCallingIdentity();
6872        try {
6873            UserInfo userInfo = sUserManager.getUserInfo(userId);
6874            return userInfo != null && userInfo.isEnabled();
6875        } finally {
6876            Binder.restoreCallingIdentity(callingId);
6877        }
6878    }
6879
6880    /**
6881     * Filter out activities with systemUserOnly flag set, when current user is not System.
6882     *
6883     * @return filtered list
6884     */
6885    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6886        if (userId == UserHandle.USER_SYSTEM) {
6887            return resolveInfos;
6888        }
6889        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6890            ResolveInfo info = resolveInfos.get(i);
6891            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6892                resolveInfos.remove(i);
6893            }
6894        }
6895        return resolveInfos;
6896    }
6897
6898    /**
6899     * Filters out ephemeral activities.
6900     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6901     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6902     *
6903     * @param resolveInfos The pre-filtered list of resolved activities
6904     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6905     *          is performed.
6906     * @return A filtered list of resolved activities.
6907     */
6908    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6909            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
6910        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6911            final ResolveInfo info = resolveInfos.get(i);
6912            // allow activities that are defined in the provided package
6913            if (allowDynamicSplits
6914                    && info.activityInfo.splitName != null
6915                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6916                            info.activityInfo.splitName)) {
6917                // requested activity is defined in a split that hasn't been installed yet.
6918                // add the installer to the resolve list
6919                if (DEBUG_INSTALL) {
6920                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6921                }
6922                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6923                final ComponentName installFailureActivity = findInstallFailureActivity(
6924                        info.activityInfo.packageName,  filterCallingUid, userId);
6925                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6926                        info.activityInfo.packageName, info.activityInfo.splitName,
6927                        installFailureActivity,
6928                        info.activityInfo.applicationInfo.versionCode,
6929                        null /*failureIntent*/);
6930                // make sure this resolver is the default
6931                installerInfo.isDefault = true;
6932                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6933                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6934                // add a non-generic filter
6935                installerInfo.filter = new IntentFilter();
6936                // load resources from the correct package
6937                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6938                resolveInfos.set(i, installerInfo);
6939                continue;
6940            }
6941            // caller is a full app, don't need to apply any other filtering
6942            if (ephemeralPkgName == null) {
6943                continue;
6944            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6945                // caller is same app; don't need to apply any other filtering
6946                continue;
6947            }
6948            // allow activities that have been explicitly exposed to ephemeral apps
6949            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6950            if (!isEphemeralApp
6951                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6952                continue;
6953            }
6954            resolveInfos.remove(i);
6955        }
6956        return resolveInfos;
6957    }
6958
6959    /**
6960     * Returns the activity component that can handle install failures.
6961     * <p>By default, the instant application installer handles failures. However, an
6962     * application may want to handle failures on its own. Applications do this by
6963     * creating an activity with an intent filter that handles the action
6964     * {@link Intent#ACTION_INSTALL_FAILURE}.
6965     */
6966    private @Nullable ComponentName findInstallFailureActivity(
6967            String packageName, int filterCallingUid, int userId) {
6968        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6969        failureActivityIntent.setPackage(packageName);
6970        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
6971        final List<ResolveInfo> result = queryIntentActivitiesInternal(
6972                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
6973                false /*resolveForStart*/, false /*allowDynamicSplits*/);
6974        final int NR = result.size();
6975        if (NR > 0) {
6976            for (int i = 0; i < NR; i++) {
6977                final ResolveInfo info = result.get(i);
6978                if (info.activityInfo.splitName != null) {
6979                    continue;
6980                }
6981                return new ComponentName(packageName, info.activityInfo.name);
6982            }
6983        }
6984        return null;
6985    }
6986
6987    /**
6988     * @param resolveInfos list of resolve infos in descending priority order
6989     * @return if the list contains a resolve info with non-negative priority
6990     */
6991    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6992        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6993    }
6994
6995    private static boolean hasWebURI(Intent intent) {
6996        if (intent.getData() == null) {
6997            return false;
6998        }
6999        final String scheme = intent.getScheme();
7000        if (TextUtils.isEmpty(scheme)) {
7001            return false;
7002        }
7003        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7004    }
7005
7006    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7007            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7008            int userId) {
7009        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7010
7011        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7012            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7013                    candidates.size());
7014        }
7015
7016        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7017        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7018        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7019        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7020        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7021        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7022
7023        synchronized (mPackages) {
7024            final int count = candidates.size();
7025            // First, try to use linked apps. Partition the candidates into four lists:
7026            // one for the final results, one for the "do not use ever", one for "undefined status"
7027            // and finally one for "browser app type".
7028            for (int n=0; n<count; n++) {
7029                ResolveInfo info = candidates.get(n);
7030                String packageName = info.activityInfo.packageName;
7031                PackageSetting ps = mSettings.mPackages.get(packageName);
7032                if (ps != null) {
7033                    // Add to the special match all list (Browser use case)
7034                    if (info.handleAllWebDataURI) {
7035                        matchAllList.add(info);
7036                        continue;
7037                    }
7038                    // Try to get the status from User settings first
7039                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7040                    int status = (int)(packedStatus >> 32);
7041                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7042                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7043                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7044                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7045                                    + " : linkgen=" + linkGeneration);
7046                        }
7047                        // Use link-enabled generation as preferredOrder, i.e.
7048                        // prefer newly-enabled over earlier-enabled.
7049                        info.preferredOrder = linkGeneration;
7050                        alwaysList.add(info);
7051                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7052                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7053                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7054                        }
7055                        neverList.add(info);
7056                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7057                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7058                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7059                        }
7060                        alwaysAskList.add(info);
7061                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7062                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7063                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7064                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7065                        }
7066                        undefinedList.add(info);
7067                    }
7068                }
7069            }
7070
7071            // We'll want to include browser possibilities in a few cases
7072            boolean includeBrowser = false;
7073
7074            // First try to add the "always" resolution(s) for the current user, if any
7075            if (alwaysList.size() > 0) {
7076                result.addAll(alwaysList);
7077            } else {
7078                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7079                result.addAll(undefinedList);
7080                // Maybe add one for the other profile.
7081                if (xpDomainInfo != null && (
7082                        xpDomainInfo.bestDomainVerificationStatus
7083                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7084                    result.add(xpDomainInfo.resolveInfo);
7085                }
7086                includeBrowser = true;
7087            }
7088
7089            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7090            // If there were 'always' entries their preferred order has been set, so we also
7091            // back that off to make the alternatives equivalent
7092            if (alwaysAskList.size() > 0) {
7093                for (ResolveInfo i : result) {
7094                    i.preferredOrder = 0;
7095                }
7096                result.addAll(alwaysAskList);
7097                includeBrowser = true;
7098            }
7099
7100            if (includeBrowser) {
7101                // Also add browsers (all of them or only the default one)
7102                if (DEBUG_DOMAIN_VERIFICATION) {
7103                    Slog.v(TAG, "   ...including browsers in candidate set");
7104                }
7105                if ((matchFlags & MATCH_ALL) != 0) {
7106                    result.addAll(matchAllList);
7107                } else {
7108                    // Browser/generic handling case.  If there's a default browser, go straight
7109                    // to that (but only if there is no other higher-priority match).
7110                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7111                    int maxMatchPrio = 0;
7112                    ResolveInfo defaultBrowserMatch = null;
7113                    final int numCandidates = matchAllList.size();
7114                    for (int n = 0; n < numCandidates; n++) {
7115                        ResolveInfo info = matchAllList.get(n);
7116                        // track the highest overall match priority...
7117                        if (info.priority > maxMatchPrio) {
7118                            maxMatchPrio = info.priority;
7119                        }
7120                        // ...and the highest-priority default browser match
7121                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7122                            if (defaultBrowserMatch == null
7123                                    || (defaultBrowserMatch.priority < info.priority)) {
7124                                if (debug) {
7125                                    Slog.v(TAG, "Considering default browser match " + info);
7126                                }
7127                                defaultBrowserMatch = info;
7128                            }
7129                        }
7130                    }
7131                    if (defaultBrowserMatch != null
7132                            && defaultBrowserMatch.priority >= maxMatchPrio
7133                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7134                    {
7135                        if (debug) {
7136                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7137                        }
7138                        result.add(defaultBrowserMatch);
7139                    } else {
7140                        result.addAll(matchAllList);
7141                    }
7142                }
7143
7144                // If there is nothing selected, add all candidates and remove the ones that the user
7145                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7146                if (result.size() == 0) {
7147                    result.addAll(candidates);
7148                    result.removeAll(neverList);
7149                }
7150            }
7151        }
7152        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7153            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7154                    result.size());
7155            for (ResolveInfo info : result) {
7156                Slog.v(TAG, "  + " + info.activityInfo);
7157            }
7158        }
7159        return result;
7160    }
7161
7162    // Returns a packed value as a long:
7163    //
7164    // high 'int'-sized word: link status: undefined/ask/never/always.
7165    // low 'int'-sized word: relative priority among 'always' results.
7166    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7167        long result = ps.getDomainVerificationStatusForUser(userId);
7168        // if none available, get the master status
7169        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7170            if (ps.getIntentFilterVerificationInfo() != null) {
7171                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7172            }
7173        }
7174        return result;
7175    }
7176
7177    private ResolveInfo querySkipCurrentProfileIntents(
7178            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7179            int flags, int sourceUserId) {
7180        if (matchingFilters != null) {
7181            int size = matchingFilters.size();
7182            for (int i = 0; i < size; i ++) {
7183                CrossProfileIntentFilter filter = matchingFilters.get(i);
7184                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7185                    // Checking if there are activities in the target user that can handle the
7186                    // intent.
7187                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7188                            resolvedType, flags, sourceUserId);
7189                    if (resolveInfo != null) {
7190                        return resolveInfo;
7191                    }
7192                }
7193            }
7194        }
7195        return null;
7196    }
7197
7198    // Return matching ResolveInfo in target user if any.
7199    private ResolveInfo queryCrossProfileIntents(
7200            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7201            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7202        if (matchingFilters != null) {
7203            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7204            // match the same intent. For performance reasons, it is better not to
7205            // run queryIntent twice for the same userId
7206            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7207            int size = matchingFilters.size();
7208            for (int i = 0; i < size; i++) {
7209                CrossProfileIntentFilter filter = matchingFilters.get(i);
7210                int targetUserId = filter.getTargetUserId();
7211                boolean skipCurrentProfile =
7212                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7213                boolean skipCurrentProfileIfNoMatchFound =
7214                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7215                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7216                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7217                    // Checking if there are activities in the target user that can handle the
7218                    // intent.
7219                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7220                            resolvedType, flags, sourceUserId);
7221                    if (resolveInfo != null) return resolveInfo;
7222                    alreadyTriedUserIds.put(targetUserId, true);
7223                }
7224            }
7225        }
7226        return null;
7227    }
7228
7229    /**
7230     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7231     * will forward the intent to the filter's target user.
7232     * Otherwise, returns null.
7233     */
7234    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7235            String resolvedType, int flags, int sourceUserId) {
7236        int targetUserId = filter.getTargetUserId();
7237        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7238                resolvedType, flags, targetUserId);
7239        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7240            // If all the matches in the target profile are suspended, return null.
7241            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7242                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7243                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7244                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7245                            targetUserId);
7246                }
7247            }
7248        }
7249        return null;
7250    }
7251
7252    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7253            int sourceUserId, int targetUserId) {
7254        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7255        long ident = Binder.clearCallingIdentity();
7256        boolean targetIsProfile;
7257        try {
7258            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7259        } finally {
7260            Binder.restoreCallingIdentity(ident);
7261        }
7262        String className;
7263        if (targetIsProfile) {
7264            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7265        } else {
7266            className = FORWARD_INTENT_TO_PARENT;
7267        }
7268        ComponentName forwardingActivityComponentName = new ComponentName(
7269                mAndroidApplication.packageName, className);
7270        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7271                sourceUserId);
7272        if (!targetIsProfile) {
7273            forwardingActivityInfo.showUserIcon = targetUserId;
7274            forwardingResolveInfo.noResourceId = true;
7275        }
7276        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7277        forwardingResolveInfo.priority = 0;
7278        forwardingResolveInfo.preferredOrder = 0;
7279        forwardingResolveInfo.match = 0;
7280        forwardingResolveInfo.isDefault = true;
7281        forwardingResolveInfo.filter = filter;
7282        forwardingResolveInfo.targetUserId = targetUserId;
7283        return forwardingResolveInfo;
7284    }
7285
7286    @Override
7287    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7288            Intent[] specifics, String[] specificTypes, Intent intent,
7289            String resolvedType, int flags, int userId) {
7290        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7291                specificTypes, intent, resolvedType, flags, userId));
7292    }
7293
7294    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7295            Intent[] specifics, String[] specificTypes, Intent intent,
7296            String resolvedType, int flags, int userId) {
7297        if (!sUserManager.exists(userId)) return Collections.emptyList();
7298        final int callingUid = Binder.getCallingUid();
7299        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7300                false /*includeInstantApps*/);
7301        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7302                false /*requireFullPermission*/, false /*checkShell*/,
7303                "query intent activity options");
7304        final String resultsAction = intent.getAction();
7305
7306        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7307                | PackageManager.GET_RESOLVED_FILTER, userId);
7308
7309        if (DEBUG_INTENT_MATCHING) {
7310            Log.v(TAG, "Query " + intent + ": " + results);
7311        }
7312
7313        int specificsPos = 0;
7314        int N;
7315
7316        // todo: note that the algorithm used here is O(N^2).  This
7317        // isn't a problem in our current environment, but if we start running
7318        // into situations where we have more than 5 or 10 matches then this
7319        // should probably be changed to something smarter...
7320
7321        // First we go through and resolve each of the specific items
7322        // that were supplied, taking care of removing any corresponding
7323        // duplicate items in the generic resolve list.
7324        if (specifics != null) {
7325            for (int i=0; i<specifics.length; i++) {
7326                final Intent sintent = specifics[i];
7327                if (sintent == null) {
7328                    continue;
7329                }
7330
7331                if (DEBUG_INTENT_MATCHING) {
7332                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7333                }
7334
7335                String action = sintent.getAction();
7336                if (resultsAction != null && resultsAction.equals(action)) {
7337                    // If this action was explicitly requested, then don't
7338                    // remove things that have it.
7339                    action = null;
7340                }
7341
7342                ResolveInfo ri = null;
7343                ActivityInfo ai = null;
7344
7345                ComponentName comp = sintent.getComponent();
7346                if (comp == null) {
7347                    ri = resolveIntent(
7348                        sintent,
7349                        specificTypes != null ? specificTypes[i] : null,
7350                            flags, userId);
7351                    if (ri == null) {
7352                        continue;
7353                    }
7354                    if (ri == mResolveInfo) {
7355                        // ACK!  Must do something better with this.
7356                    }
7357                    ai = ri.activityInfo;
7358                    comp = new ComponentName(ai.applicationInfo.packageName,
7359                            ai.name);
7360                } else {
7361                    ai = getActivityInfo(comp, flags, userId);
7362                    if (ai == null) {
7363                        continue;
7364                    }
7365                }
7366
7367                // Look for any generic query activities that are duplicates
7368                // of this specific one, and remove them from the results.
7369                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7370                N = results.size();
7371                int j;
7372                for (j=specificsPos; j<N; j++) {
7373                    ResolveInfo sri = results.get(j);
7374                    if ((sri.activityInfo.name.equals(comp.getClassName())
7375                            && sri.activityInfo.applicationInfo.packageName.equals(
7376                                    comp.getPackageName()))
7377                        || (action != null && sri.filter.matchAction(action))) {
7378                        results.remove(j);
7379                        if (DEBUG_INTENT_MATCHING) Log.v(
7380                            TAG, "Removing duplicate item from " + j
7381                            + " due to specific " + specificsPos);
7382                        if (ri == null) {
7383                            ri = sri;
7384                        }
7385                        j--;
7386                        N--;
7387                    }
7388                }
7389
7390                // Add this specific item to its proper place.
7391                if (ri == null) {
7392                    ri = new ResolveInfo();
7393                    ri.activityInfo = ai;
7394                }
7395                results.add(specificsPos, ri);
7396                ri.specificIndex = i;
7397                specificsPos++;
7398            }
7399        }
7400
7401        // Now we go through the remaining generic results and remove any
7402        // duplicate actions that are found here.
7403        N = results.size();
7404        for (int i=specificsPos; i<N-1; i++) {
7405            final ResolveInfo rii = results.get(i);
7406            if (rii.filter == null) {
7407                continue;
7408            }
7409
7410            // Iterate over all of the actions of this result's intent
7411            // filter...  typically this should be just one.
7412            final Iterator<String> it = rii.filter.actionsIterator();
7413            if (it == null) {
7414                continue;
7415            }
7416            while (it.hasNext()) {
7417                final String action = it.next();
7418                if (resultsAction != null && resultsAction.equals(action)) {
7419                    // If this action was explicitly requested, then don't
7420                    // remove things that have it.
7421                    continue;
7422                }
7423                for (int j=i+1; j<N; j++) {
7424                    final ResolveInfo rij = results.get(j);
7425                    if (rij.filter != null && rij.filter.hasAction(action)) {
7426                        results.remove(j);
7427                        if (DEBUG_INTENT_MATCHING) Log.v(
7428                            TAG, "Removing duplicate item from " + j
7429                            + " due to action " + action + " at " + i);
7430                        j--;
7431                        N--;
7432                    }
7433                }
7434            }
7435
7436            // If the caller didn't request filter information, drop it now
7437            // so we don't have to marshall/unmarshall it.
7438            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7439                rii.filter = null;
7440            }
7441        }
7442
7443        // Filter out the caller activity if so requested.
7444        if (caller != null) {
7445            N = results.size();
7446            for (int i=0; i<N; i++) {
7447                ActivityInfo ainfo = results.get(i).activityInfo;
7448                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7449                        && caller.getClassName().equals(ainfo.name)) {
7450                    results.remove(i);
7451                    break;
7452                }
7453            }
7454        }
7455
7456        // If the caller didn't request filter information,
7457        // drop them now so we don't have to
7458        // marshall/unmarshall it.
7459        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7460            N = results.size();
7461            for (int i=0; i<N; i++) {
7462                results.get(i).filter = null;
7463            }
7464        }
7465
7466        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7467        return results;
7468    }
7469
7470    @Override
7471    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7472            String resolvedType, int flags, int userId) {
7473        return new ParceledListSlice<>(
7474                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7475                        false /*allowDynamicSplits*/));
7476    }
7477
7478    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7479            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7480        if (!sUserManager.exists(userId)) return Collections.emptyList();
7481        final int callingUid = Binder.getCallingUid();
7482        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7483                false /*requireFullPermission*/, false /*checkShell*/,
7484                "query intent receivers");
7485        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7486        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7487                false /*includeInstantApps*/);
7488        ComponentName comp = intent.getComponent();
7489        if (comp == null) {
7490            if (intent.getSelector() != null) {
7491                intent = intent.getSelector();
7492                comp = intent.getComponent();
7493            }
7494        }
7495        if (comp != null) {
7496            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7497            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7498            if (ai != null) {
7499                // When specifying an explicit component, we prevent the activity from being
7500                // used when either 1) the calling package is normal and the activity is within
7501                // an instant application or 2) the calling package is ephemeral and the
7502                // activity is not visible to instant applications.
7503                final boolean matchInstantApp =
7504                        (flags & PackageManager.MATCH_INSTANT) != 0;
7505                final boolean matchVisibleToInstantAppOnly =
7506                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7507                final boolean matchExplicitlyVisibleOnly =
7508                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7509                final boolean isCallerInstantApp =
7510                        instantAppPkgName != null;
7511                final boolean isTargetSameInstantApp =
7512                        comp.getPackageName().equals(instantAppPkgName);
7513                final boolean isTargetInstantApp =
7514                        (ai.applicationInfo.privateFlags
7515                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7516                final boolean isTargetVisibleToInstantApp =
7517                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7518                final boolean isTargetExplicitlyVisibleToInstantApp =
7519                        isTargetVisibleToInstantApp
7520                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7521                final boolean isTargetHiddenFromInstantApp =
7522                        !isTargetVisibleToInstantApp
7523                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7524                final boolean blockResolution =
7525                        !isTargetSameInstantApp
7526                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7527                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7528                                        && isTargetHiddenFromInstantApp));
7529                if (!blockResolution) {
7530                    ResolveInfo ri = new ResolveInfo();
7531                    ri.activityInfo = ai;
7532                    list.add(ri);
7533                }
7534            }
7535            return applyPostResolutionFilter(
7536                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7537        }
7538
7539        // reader
7540        synchronized (mPackages) {
7541            String pkgName = intent.getPackage();
7542            if (pkgName == null) {
7543                final List<ResolveInfo> result =
7544                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7545                return applyPostResolutionFilter(
7546                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7547            }
7548            final PackageParser.Package pkg = mPackages.get(pkgName);
7549            if (pkg != null) {
7550                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7551                        intent, resolvedType, flags, pkg.receivers, userId);
7552                return applyPostResolutionFilter(
7553                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
7554            }
7555            return Collections.emptyList();
7556        }
7557    }
7558
7559    @Override
7560    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7561        final int callingUid = Binder.getCallingUid();
7562        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7563    }
7564
7565    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7566            int userId, int callingUid) {
7567        if (!sUserManager.exists(userId)) return null;
7568        flags = updateFlagsForResolve(
7569                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7570        List<ResolveInfo> query = queryIntentServicesInternal(
7571                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7572        if (query != null) {
7573            if (query.size() >= 1) {
7574                // If there is more than one service with the same priority,
7575                // just arbitrarily pick the first one.
7576                return query.get(0);
7577            }
7578        }
7579        return null;
7580    }
7581
7582    @Override
7583    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7584            String resolvedType, int flags, int userId) {
7585        final int callingUid = Binder.getCallingUid();
7586        return new ParceledListSlice<>(queryIntentServicesInternal(
7587                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7588    }
7589
7590    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7591            String resolvedType, int flags, int userId, int callingUid,
7592            boolean includeInstantApps) {
7593        if (!sUserManager.exists(userId)) return Collections.emptyList();
7594        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7595                false /*requireFullPermission*/, false /*checkShell*/,
7596                "query intent receivers");
7597        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7598        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7599        ComponentName comp = intent.getComponent();
7600        if (comp == null) {
7601            if (intent.getSelector() != null) {
7602                intent = intent.getSelector();
7603                comp = intent.getComponent();
7604            }
7605        }
7606        if (comp != null) {
7607            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7608            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7609            if (si != null) {
7610                // When specifying an explicit component, we prevent the service from being
7611                // used when either 1) the service is in an instant application and the
7612                // caller is not the same instant application or 2) the calling package is
7613                // ephemeral and the activity is not visible to ephemeral applications.
7614                final boolean matchInstantApp =
7615                        (flags & PackageManager.MATCH_INSTANT) != 0;
7616                final boolean matchVisibleToInstantAppOnly =
7617                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7618                final boolean isCallerInstantApp =
7619                        instantAppPkgName != null;
7620                final boolean isTargetSameInstantApp =
7621                        comp.getPackageName().equals(instantAppPkgName);
7622                final boolean isTargetInstantApp =
7623                        (si.applicationInfo.privateFlags
7624                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7625                final boolean isTargetHiddenFromInstantApp =
7626                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7627                final boolean blockResolution =
7628                        !isTargetSameInstantApp
7629                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7630                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7631                                        && isTargetHiddenFromInstantApp));
7632                if (!blockResolution) {
7633                    final ResolveInfo ri = new ResolveInfo();
7634                    ri.serviceInfo = si;
7635                    list.add(ri);
7636                }
7637            }
7638            return list;
7639        }
7640
7641        // reader
7642        synchronized (mPackages) {
7643            String pkgName = intent.getPackage();
7644            if (pkgName == null) {
7645                return applyPostServiceResolutionFilter(
7646                        mServices.queryIntent(intent, resolvedType, flags, userId),
7647                        instantAppPkgName);
7648            }
7649            final PackageParser.Package pkg = mPackages.get(pkgName);
7650            if (pkg != null) {
7651                return applyPostServiceResolutionFilter(
7652                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7653                                userId),
7654                        instantAppPkgName);
7655            }
7656            return Collections.emptyList();
7657        }
7658    }
7659
7660    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7661            String instantAppPkgName) {
7662        if (instantAppPkgName == null) {
7663            return resolveInfos;
7664        }
7665        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7666            final ResolveInfo info = resolveInfos.get(i);
7667            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7668            // allow services that are defined in the provided package
7669            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7670                if (info.serviceInfo.splitName != null
7671                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7672                                info.serviceInfo.splitName)) {
7673                    // requested service is defined in a split that hasn't been installed yet.
7674                    // add the installer to the resolve list
7675                    if (DEBUG_EPHEMERAL) {
7676                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7677                    }
7678                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7679                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7680                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7681                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
7682                            null /*failureIntent*/);
7683                    // make sure this resolver is the default
7684                    installerInfo.isDefault = true;
7685                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7686                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7687                    // add a non-generic filter
7688                    installerInfo.filter = new IntentFilter();
7689                    // load resources from the correct package
7690                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7691                    resolveInfos.set(i, installerInfo);
7692                }
7693                continue;
7694            }
7695            // allow services that have been explicitly exposed to ephemeral apps
7696            if (!isEphemeralApp
7697                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7698                continue;
7699            }
7700            resolveInfos.remove(i);
7701        }
7702        return resolveInfos;
7703    }
7704
7705    @Override
7706    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7707            String resolvedType, int flags, int userId) {
7708        return new ParceledListSlice<>(
7709                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7710    }
7711
7712    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7713            Intent intent, String resolvedType, int flags, int userId) {
7714        if (!sUserManager.exists(userId)) return Collections.emptyList();
7715        final int callingUid = Binder.getCallingUid();
7716        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7717        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7718                false /*includeInstantApps*/);
7719        ComponentName comp = intent.getComponent();
7720        if (comp == null) {
7721            if (intent.getSelector() != null) {
7722                intent = intent.getSelector();
7723                comp = intent.getComponent();
7724            }
7725        }
7726        if (comp != null) {
7727            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7728            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7729            if (pi != null) {
7730                // When specifying an explicit component, we prevent the provider from being
7731                // used when either 1) the provider is in an instant application and the
7732                // caller is not the same instant application or 2) the calling package is an
7733                // instant application and the provider is not visible to instant applications.
7734                final boolean matchInstantApp =
7735                        (flags & PackageManager.MATCH_INSTANT) != 0;
7736                final boolean matchVisibleToInstantAppOnly =
7737                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7738                final boolean isCallerInstantApp =
7739                        instantAppPkgName != null;
7740                final boolean isTargetSameInstantApp =
7741                        comp.getPackageName().equals(instantAppPkgName);
7742                final boolean isTargetInstantApp =
7743                        (pi.applicationInfo.privateFlags
7744                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7745                final boolean isTargetHiddenFromInstantApp =
7746                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7747                final boolean blockResolution =
7748                        !isTargetSameInstantApp
7749                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7750                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7751                                        && isTargetHiddenFromInstantApp));
7752                if (!blockResolution) {
7753                    final ResolveInfo ri = new ResolveInfo();
7754                    ri.providerInfo = pi;
7755                    list.add(ri);
7756                }
7757            }
7758            return list;
7759        }
7760
7761        // reader
7762        synchronized (mPackages) {
7763            String pkgName = intent.getPackage();
7764            if (pkgName == null) {
7765                return applyPostContentProviderResolutionFilter(
7766                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7767                        instantAppPkgName);
7768            }
7769            final PackageParser.Package pkg = mPackages.get(pkgName);
7770            if (pkg != null) {
7771                return applyPostContentProviderResolutionFilter(
7772                        mProviders.queryIntentForPackage(
7773                        intent, resolvedType, flags, pkg.providers, userId),
7774                        instantAppPkgName);
7775            }
7776            return Collections.emptyList();
7777        }
7778    }
7779
7780    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7781            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7782        if (instantAppPkgName == null) {
7783            return resolveInfos;
7784        }
7785        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7786            final ResolveInfo info = resolveInfos.get(i);
7787            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7788            // allow providers that are defined in the provided package
7789            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7790                if (info.providerInfo.splitName != null
7791                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7792                                info.providerInfo.splitName)) {
7793                    // requested provider is defined in a split that hasn't been installed yet.
7794                    // add the installer to the resolve list
7795                    if (DEBUG_EPHEMERAL) {
7796                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7797                    }
7798                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7799                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7800                            info.providerInfo.packageName, info.providerInfo.splitName,
7801                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
7802                            null /*failureIntent*/);
7803                    // make sure this resolver is the default
7804                    installerInfo.isDefault = true;
7805                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7806                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7807                    // add a non-generic filter
7808                    installerInfo.filter = new IntentFilter();
7809                    // load resources from the correct package
7810                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7811                    resolveInfos.set(i, installerInfo);
7812                }
7813                continue;
7814            }
7815            // allow providers that have been explicitly exposed to instant applications
7816            if (!isEphemeralApp
7817                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7818                continue;
7819            }
7820            resolveInfos.remove(i);
7821        }
7822        return resolveInfos;
7823    }
7824
7825    @Override
7826    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7827        final int callingUid = Binder.getCallingUid();
7828        if (getInstantAppPackageName(callingUid) != null) {
7829            return ParceledListSlice.emptyList();
7830        }
7831        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7832        flags = updateFlagsForPackage(flags, userId, null);
7833        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7834        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7835                true /* requireFullPermission */, false /* checkShell */,
7836                "get installed packages");
7837
7838        // writer
7839        synchronized (mPackages) {
7840            ArrayList<PackageInfo> list;
7841            if (listUninstalled) {
7842                list = new ArrayList<>(mSettings.mPackages.size());
7843                for (PackageSetting ps : mSettings.mPackages.values()) {
7844                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7845                        continue;
7846                    }
7847                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7848                        continue;
7849                    }
7850                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7851                    if (pi != null) {
7852                        list.add(pi);
7853                    }
7854                }
7855            } else {
7856                list = new ArrayList<>(mPackages.size());
7857                for (PackageParser.Package p : mPackages.values()) {
7858                    final PackageSetting ps = (PackageSetting) p.mExtras;
7859                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7860                        continue;
7861                    }
7862                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7863                        continue;
7864                    }
7865                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7866                            p.mExtras, flags, userId);
7867                    if (pi != null) {
7868                        list.add(pi);
7869                    }
7870                }
7871            }
7872
7873            return new ParceledListSlice<>(list);
7874        }
7875    }
7876
7877    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7878            String[] permissions, boolean[] tmp, int flags, int userId) {
7879        int numMatch = 0;
7880        final PermissionsState permissionsState = ps.getPermissionsState();
7881        for (int i=0; i<permissions.length; i++) {
7882            final String permission = permissions[i];
7883            if (permissionsState.hasPermission(permission, userId)) {
7884                tmp[i] = true;
7885                numMatch++;
7886            } else {
7887                tmp[i] = false;
7888            }
7889        }
7890        if (numMatch == 0) {
7891            return;
7892        }
7893        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7894
7895        // The above might return null in cases of uninstalled apps or install-state
7896        // skew across users/profiles.
7897        if (pi != null) {
7898            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7899                if (numMatch == permissions.length) {
7900                    pi.requestedPermissions = permissions;
7901                } else {
7902                    pi.requestedPermissions = new String[numMatch];
7903                    numMatch = 0;
7904                    for (int i=0; i<permissions.length; i++) {
7905                        if (tmp[i]) {
7906                            pi.requestedPermissions[numMatch] = permissions[i];
7907                            numMatch++;
7908                        }
7909                    }
7910                }
7911            }
7912            list.add(pi);
7913        }
7914    }
7915
7916    @Override
7917    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7918            String[] permissions, int flags, int userId) {
7919        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7920        flags = updateFlagsForPackage(flags, userId, permissions);
7921        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7922                true /* requireFullPermission */, false /* checkShell */,
7923                "get packages holding permissions");
7924        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7925
7926        // writer
7927        synchronized (mPackages) {
7928            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7929            boolean[] tmpBools = new boolean[permissions.length];
7930            if (listUninstalled) {
7931                for (PackageSetting ps : mSettings.mPackages.values()) {
7932                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7933                            userId);
7934                }
7935            } else {
7936                for (PackageParser.Package pkg : mPackages.values()) {
7937                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7938                    if (ps != null) {
7939                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7940                                userId);
7941                    }
7942                }
7943            }
7944
7945            return new ParceledListSlice<PackageInfo>(list);
7946        }
7947    }
7948
7949    @Override
7950    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7951        final int callingUid = Binder.getCallingUid();
7952        if (getInstantAppPackageName(callingUid) != null) {
7953            return ParceledListSlice.emptyList();
7954        }
7955        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7956        flags = updateFlagsForApplication(flags, userId, null);
7957        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7958
7959        // writer
7960        synchronized (mPackages) {
7961            ArrayList<ApplicationInfo> list;
7962            if (listUninstalled) {
7963                list = new ArrayList<>(mSettings.mPackages.size());
7964                for (PackageSetting ps : mSettings.mPackages.values()) {
7965                    ApplicationInfo ai;
7966                    int effectiveFlags = flags;
7967                    if (ps.isSystem()) {
7968                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7969                    }
7970                    if (ps.pkg != null) {
7971                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7972                            continue;
7973                        }
7974                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7975                            continue;
7976                        }
7977                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7978                                ps.readUserState(userId), userId);
7979                        if (ai != null) {
7980                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7981                        }
7982                    } else {
7983                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7984                        // and already converts to externally visible package name
7985                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7986                                callingUid, effectiveFlags, userId);
7987                    }
7988                    if (ai != null) {
7989                        list.add(ai);
7990                    }
7991                }
7992            } else {
7993                list = new ArrayList<>(mPackages.size());
7994                for (PackageParser.Package p : mPackages.values()) {
7995                    if (p.mExtras != null) {
7996                        PackageSetting ps = (PackageSetting) p.mExtras;
7997                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7998                            continue;
7999                        }
8000                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8001                            continue;
8002                        }
8003                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8004                                ps.readUserState(userId), userId);
8005                        if (ai != null) {
8006                            ai.packageName = resolveExternalPackageNameLPr(p);
8007                            list.add(ai);
8008                        }
8009                    }
8010                }
8011            }
8012
8013            return new ParceledListSlice<>(list);
8014        }
8015    }
8016
8017    @Override
8018    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8019        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8020            return null;
8021        }
8022        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8023            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8024                    "getEphemeralApplications");
8025        }
8026        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8027                true /* requireFullPermission */, false /* checkShell */,
8028                "getEphemeralApplications");
8029        synchronized (mPackages) {
8030            List<InstantAppInfo> instantApps = mInstantAppRegistry
8031                    .getInstantAppsLPr(userId);
8032            if (instantApps != null) {
8033                return new ParceledListSlice<>(instantApps);
8034            }
8035        }
8036        return null;
8037    }
8038
8039    @Override
8040    public boolean isInstantApp(String packageName, int userId) {
8041        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8042                true /* requireFullPermission */, false /* checkShell */,
8043                "isInstantApp");
8044        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8045            return false;
8046        }
8047
8048        synchronized (mPackages) {
8049            int callingUid = Binder.getCallingUid();
8050            if (Process.isIsolated(callingUid)) {
8051                callingUid = mIsolatedOwners.get(callingUid);
8052            }
8053            final PackageSetting ps = mSettings.mPackages.get(packageName);
8054            PackageParser.Package pkg = mPackages.get(packageName);
8055            final boolean returnAllowed =
8056                    ps != null
8057                    && (isCallerSameApp(packageName, callingUid)
8058                            || canViewInstantApps(callingUid, userId)
8059                            || mInstantAppRegistry.isInstantAccessGranted(
8060                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8061            if (returnAllowed) {
8062                return ps.getInstantApp(userId);
8063            }
8064        }
8065        return false;
8066    }
8067
8068    @Override
8069    public byte[] getInstantAppCookie(String packageName, int userId) {
8070        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8071            return null;
8072        }
8073
8074        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8075                true /* requireFullPermission */, false /* checkShell */,
8076                "getInstantAppCookie");
8077        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8078            return null;
8079        }
8080        synchronized (mPackages) {
8081            return mInstantAppRegistry.getInstantAppCookieLPw(
8082                    packageName, userId);
8083        }
8084    }
8085
8086    @Override
8087    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8088        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8089            return true;
8090        }
8091
8092        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8093                true /* requireFullPermission */, true /* checkShell */,
8094                "setInstantAppCookie");
8095        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8096            return false;
8097        }
8098        synchronized (mPackages) {
8099            return mInstantAppRegistry.setInstantAppCookieLPw(
8100                    packageName, cookie, userId);
8101        }
8102    }
8103
8104    @Override
8105    public Bitmap getInstantAppIcon(String packageName, int userId) {
8106        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8107            return null;
8108        }
8109
8110        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8111            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8112                    "getInstantAppIcon");
8113        }
8114        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8115                true /* requireFullPermission */, false /* checkShell */,
8116                "getInstantAppIcon");
8117
8118        synchronized (mPackages) {
8119            return mInstantAppRegistry.getInstantAppIconLPw(
8120                    packageName, userId);
8121        }
8122    }
8123
8124    private boolean isCallerSameApp(String packageName, int uid) {
8125        PackageParser.Package pkg = mPackages.get(packageName);
8126        return pkg != null
8127                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8128    }
8129
8130    @Override
8131    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8132        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8133            return ParceledListSlice.emptyList();
8134        }
8135        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8136    }
8137
8138    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8139        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8140
8141        // reader
8142        synchronized (mPackages) {
8143            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8144            final int userId = UserHandle.getCallingUserId();
8145            while (i.hasNext()) {
8146                final PackageParser.Package p = i.next();
8147                if (p.applicationInfo == null) continue;
8148
8149                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8150                        && !p.applicationInfo.isDirectBootAware();
8151                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8152                        && p.applicationInfo.isDirectBootAware();
8153
8154                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8155                        && (!mSafeMode || isSystemApp(p))
8156                        && (matchesUnaware || matchesAware)) {
8157                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8158                    if (ps != null) {
8159                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8160                                ps.readUserState(userId), userId);
8161                        if (ai != null) {
8162                            finalList.add(ai);
8163                        }
8164                    }
8165                }
8166            }
8167        }
8168
8169        return finalList;
8170    }
8171
8172    @Override
8173    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8174        return resolveContentProviderInternal(name, flags, userId);
8175    }
8176
8177    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8178        if (!sUserManager.exists(userId)) return null;
8179        flags = updateFlagsForComponent(flags, userId, name);
8180        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8181        // reader
8182        synchronized (mPackages) {
8183            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8184            PackageSetting ps = provider != null
8185                    ? mSettings.mPackages.get(provider.owner.packageName)
8186                    : null;
8187            if (ps != null) {
8188                final boolean isInstantApp = ps.getInstantApp(userId);
8189                // normal application; filter out instant application provider
8190                if (instantAppPkgName == null && isInstantApp) {
8191                    return null;
8192                }
8193                // instant application; filter out other instant applications
8194                if (instantAppPkgName != null
8195                        && isInstantApp
8196                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8197                    return null;
8198                }
8199                // instant application; filter out non-exposed provider
8200                if (instantAppPkgName != null
8201                        && !isInstantApp
8202                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8203                    return null;
8204                }
8205                // provider not enabled
8206                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8207                    return null;
8208                }
8209                return PackageParser.generateProviderInfo(
8210                        provider, flags, ps.readUserState(userId), userId);
8211            }
8212            return null;
8213        }
8214    }
8215
8216    /**
8217     * @deprecated
8218     */
8219    @Deprecated
8220    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8221        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8222            return;
8223        }
8224        // reader
8225        synchronized (mPackages) {
8226            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8227                    .entrySet().iterator();
8228            final int userId = UserHandle.getCallingUserId();
8229            while (i.hasNext()) {
8230                Map.Entry<String, PackageParser.Provider> entry = i.next();
8231                PackageParser.Provider p = entry.getValue();
8232                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8233
8234                if (ps != null && p.syncable
8235                        && (!mSafeMode || (p.info.applicationInfo.flags
8236                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8237                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8238                            ps.readUserState(userId), userId);
8239                    if (info != null) {
8240                        outNames.add(entry.getKey());
8241                        outInfo.add(info);
8242                    }
8243                }
8244            }
8245        }
8246    }
8247
8248    @Override
8249    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8250            int uid, int flags, String metaDataKey) {
8251        final int callingUid = Binder.getCallingUid();
8252        final int userId = processName != null ? UserHandle.getUserId(uid)
8253                : UserHandle.getCallingUserId();
8254        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8255        flags = updateFlagsForComponent(flags, userId, processName);
8256        ArrayList<ProviderInfo> finalList = null;
8257        // reader
8258        synchronized (mPackages) {
8259            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8260            while (i.hasNext()) {
8261                final PackageParser.Provider p = i.next();
8262                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8263                if (ps != null && p.info.authority != null
8264                        && (processName == null
8265                                || (p.info.processName.equals(processName)
8266                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8267                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8268
8269                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8270                    // parameter.
8271                    if (metaDataKey != null
8272                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8273                        continue;
8274                    }
8275                    final ComponentName component =
8276                            new ComponentName(p.info.packageName, p.info.name);
8277                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8278                        continue;
8279                    }
8280                    if (finalList == null) {
8281                        finalList = new ArrayList<ProviderInfo>(3);
8282                    }
8283                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8284                            ps.readUserState(userId), userId);
8285                    if (info != null) {
8286                        finalList.add(info);
8287                    }
8288                }
8289            }
8290        }
8291
8292        if (finalList != null) {
8293            Collections.sort(finalList, mProviderInitOrderSorter);
8294            return new ParceledListSlice<ProviderInfo>(finalList);
8295        }
8296
8297        return ParceledListSlice.emptyList();
8298    }
8299
8300    @Override
8301    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8302        // reader
8303        synchronized (mPackages) {
8304            final int callingUid = Binder.getCallingUid();
8305            final int callingUserId = UserHandle.getUserId(callingUid);
8306            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8307            if (ps == null) return null;
8308            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8309                return null;
8310            }
8311            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8312            return PackageParser.generateInstrumentationInfo(i, flags);
8313        }
8314    }
8315
8316    @Override
8317    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8318            String targetPackage, int flags) {
8319        final int callingUid = Binder.getCallingUid();
8320        final int callingUserId = UserHandle.getUserId(callingUid);
8321        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8322        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8323            return ParceledListSlice.emptyList();
8324        }
8325        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8326    }
8327
8328    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8329            int flags) {
8330        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8331
8332        // reader
8333        synchronized (mPackages) {
8334            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8335            while (i.hasNext()) {
8336                final PackageParser.Instrumentation p = i.next();
8337                if (targetPackage == null
8338                        || targetPackage.equals(p.info.targetPackage)) {
8339                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8340                            flags);
8341                    if (ii != null) {
8342                        finalList.add(ii);
8343                    }
8344                }
8345            }
8346        }
8347
8348        return finalList;
8349    }
8350
8351    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8352        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8353        try {
8354            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8355        } finally {
8356            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8357        }
8358    }
8359
8360    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8361        final File[] files = dir.listFiles();
8362        if (ArrayUtils.isEmpty(files)) {
8363            Log.d(TAG, "No files in app dir " + dir);
8364            return;
8365        }
8366
8367        if (DEBUG_PACKAGE_SCANNING) {
8368            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8369                    + " flags=0x" + Integer.toHexString(parseFlags));
8370        }
8371        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8372                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8373                mParallelPackageParserCallback);
8374
8375        // Submit files for parsing in parallel
8376        int fileCount = 0;
8377        for (File file : files) {
8378            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8379                    && !PackageInstallerService.isStageName(file.getName());
8380            if (!isPackage) {
8381                // Ignore entries which are not packages
8382                continue;
8383            }
8384            parallelPackageParser.submit(file, parseFlags);
8385            fileCount++;
8386        }
8387
8388        // Process results one by one
8389        for (; fileCount > 0; fileCount--) {
8390            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8391            Throwable throwable = parseResult.throwable;
8392            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8393
8394            if (throwable == null) {
8395                // Static shared libraries have synthetic package names
8396                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8397                    renameStaticSharedLibraryPackage(parseResult.pkg);
8398                }
8399                try {
8400                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8401                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8402                                currentTime, null);
8403                    }
8404                } catch (PackageManagerException e) {
8405                    errorCode = e.error;
8406                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8407                }
8408            } else if (throwable instanceof PackageParser.PackageParserException) {
8409                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8410                        throwable;
8411                errorCode = e.error;
8412                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8413            } else {
8414                throw new IllegalStateException("Unexpected exception occurred while parsing "
8415                        + parseResult.scanFile, throwable);
8416            }
8417
8418            // Delete invalid userdata apps
8419            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8420                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8421                logCriticalInfo(Log.WARN,
8422                        "Deleting invalid package at " + parseResult.scanFile);
8423                removeCodePathLI(parseResult.scanFile);
8424            }
8425        }
8426        parallelPackageParser.close();
8427    }
8428
8429    private static File getSettingsProblemFile() {
8430        File dataDir = Environment.getDataDirectory();
8431        File systemDir = new File(dataDir, "system");
8432        File fname = new File(systemDir, "uiderrors.txt");
8433        return fname;
8434    }
8435
8436    public static void reportSettingsProblem(int priority, String msg) {
8437        logCriticalInfo(priority, msg);
8438    }
8439
8440    public static void logCriticalInfo(int priority, String msg) {
8441        Slog.println(priority, TAG, msg);
8442        EventLogTags.writePmCriticalInfo(msg);
8443        try {
8444            File fname = getSettingsProblemFile();
8445            FileOutputStream out = new FileOutputStream(fname, true);
8446            PrintWriter pw = new FastPrintWriter(out);
8447            SimpleDateFormat formatter = new SimpleDateFormat();
8448            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8449            pw.println(dateString + ": " + msg);
8450            pw.close();
8451            FileUtils.setPermissions(
8452                    fname.toString(),
8453                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8454                    -1, -1);
8455        } catch (java.io.IOException e) {
8456        }
8457    }
8458
8459    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8460        if (srcFile.isDirectory()) {
8461            final File baseFile = new File(pkg.baseCodePath);
8462            long maxModifiedTime = baseFile.lastModified();
8463            if (pkg.splitCodePaths != null) {
8464                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8465                    final File splitFile = new File(pkg.splitCodePaths[i]);
8466                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8467                }
8468            }
8469            return maxModifiedTime;
8470        }
8471        return srcFile.lastModified();
8472    }
8473
8474    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8475            final int policyFlags) throws PackageManagerException {
8476        // When upgrading from pre-N MR1, verify the package time stamp using the package
8477        // directory and not the APK file.
8478        final long lastModifiedTime = mIsPreNMR1Upgrade
8479                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8480        if (ps != null
8481                && ps.codePath.equals(srcFile)
8482                && ps.timeStamp == lastModifiedTime
8483                && !isCompatSignatureUpdateNeeded(pkg)
8484                && !isRecoverSignatureUpdateNeeded(pkg)) {
8485            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8486            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8487            ArraySet<PublicKey> signingKs;
8488            synchronized (mPackages) {
8489                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8490            }
8491            if (ps.signatures.mSignatures != null
8492                    && ps.signatures.mSignatures.length != 0
8493                    && signingKs != null) {
8494                // Optimization: reuse the existing cached certificates
8495                // if the package appears to be unchanged.
8496                pkg.mSignatures = ps.signatures.mSignatures;
8497                pkg.mSigningKeys = signingKs;
8498                return;
8499            }
8500
8501            Slog.w(TAG, "PackageSetting for " + ps.name
8502                    + " is missing signatures.  Collecting certs again to recover them.");
8503        } else {
8504            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8505        }
8506
8507        try {
8508            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8509            PackageParser.collectCertificates(pkg, policyFlags);
8510        } catch (PackageParserException e) {
8511            throw PackageManagerException.from(e);
8512        } finally {
8513            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8514        }
8515    }
8516
8517    /**
8518     *  Traces a package scan.
8519     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8520     */
8521    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8522            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8523        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8524        try {
8525            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8526        } finally {
8527            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8528        }
8529    }
8530
8531    /**
8532     *  Scans a package and returns the newly parsed package.
8533     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8534     */
8535    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8536            long currentTime, UserHandle user) throws PackageManagerException {
8537        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8538        PackageParser pp = new PackageParser();
8539        pp.setSeparateProcesses(mSeparateProcesses);
8540        pp.setOnlyCoreApps(mOnlyCore);
8541        pp.setDisplayMetrics(mMetrics);
8542        pp.setCallback(mPackageParserCallback);
8543
8544        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8545            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8546        }
8547
8548        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8549        final PackageParser.Package pkg;
8550        try {
8551            pkg = pp.parsePackage(scanFile, parseFlags);
8552        } catch (PackageParserException e) {
8553            throw PackageManagerException.from(e);
8554        } finally {
8555            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8556        }
8557
8558        // Static shared libraries have synthetic package names
8559        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8560            renameStaticSharedLibraryPackage(pkg);
8561        }
8562
8563        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8564    }
8565
8566    /**
8567     *  Scans a package and returns the newly parsed package.
8568     *  @throws PackageManagerException on a parse error.
8569     */
8570    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8571            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8572            throws PackageManagerException {
8573        // If the package has children and this is the first dive in the function
8574        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8575        // packages (parent and children) would be successfully scanned before the
8576        // actual scan since scanning mutates internal state and we want to atomically
8577        // install the package and its children.
8578        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8579            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8580                scanFlags |= SCAN_CHECK_ONLY;
8581            }
8582        } else {
8583            scanFlags &= ~SCAN_CHECK_ONLY;
8584        }
8585
8586        // Scan the parent
8587        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8588                scanFlags, currentTime, user);
8589
8590        // Scan the children
8591        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8592        for (int i = 0; i < childCount; i++) {
8593            PackageParser.Package childPackage = pkg.childPackages.get(i);
8594            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8595                    currentTime, user);
8596        }
8597
8598
8599        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8600            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8601        }
8602
8603        return scannedPkg;
8604    }
8605
8606    /**
8607     *  Scans a package and returns the newly parsed package.
8608     *  @throws PackageManagerException on a parse error.
8609     */
8610    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8611            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8612            throws PackageManagerException {
8613        PackageSetting ps = null;
8614        PackageSetting updatedPkg;
8615        // reader
8616        synchronized (mPackages) {
8617            // Look to see if we already know about this package.
8618            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8619            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8620                // This package has been renamed to its original name.  Let's
8621                // use that.
8622                ps = mSettings.getPackageLPr(oldName);
8623            }
8624            // If there was no original package, see one for the real package name.
8625            if (ps == null) {
8626                ps = mSettings.getPackageLPr(pkg.packageName);
8627            }
8628            // Check to see if this package could be hiding/updating a system
8629            // package.  Must look for it either under the original or real
8630            // package name depending on our state.
8631            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8632            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8633
8634            // If this is a package we don't know about on the system partition, we
8635            // may need to remove disabled child packages on the system partition
8636            // or may need to not add child packages if the parent apk is updated
8637            // on the data partition and no longer defines this child package.
8638            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8639                // If this is a parent package for an updated system app and this system
8640                // app got an OTA update which no longer defines some of the child packages
8641                // we have to prune them from the disabled system packages.
8642                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8643                if (disabledPs != null) {
8644                    final int scannedChildCount = (pkg.childPackages != null)
8645                            ? pkg.childPackages.size() : 0;
8646                    final int disabledChildCount = disabledPs.childPackageNames != null
8647                            ? disabledPs.childPackageNames.size() : 0;
8648                    for (int i = 0; i < disabledChildCount; i++) {
8649                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8650                        boolean disabledPackageAvailable = false;
8651                        for (int j = 0; j < scannedChildCount; j++) {
8652                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8653                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8654                                disabledPackageAvailable = true;
8655                                break;
8656                            }
8657                         }
8658                         if (!disabledPackageAvailable) {
8659                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8660                         }
8661                    }
8662                }
8663            }
8664        }
8665
8666        final boolean isUpdatedPkg = updatedPkg != null;
8667        final boolean isUpdatedSystemPkg = isUpdatedPkg
8668                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
8669        boolean isUpdatedPkgBetter = false;
8670        // First check if this is a system package that may involve an update
8671        if (isUpdatedSystemPkg) {
8672            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8673            // it needs to drop FLAG_PRIVILEGED.
8674            if (locationIsPrivileged(scanFile)) {
8675                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8676            } else {
8677                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8678            }
8679            // If new package is not located in "/oem" (e.g. due to an OTA),
8680            // it needs to drop FLAG_OEM.
8681            if (locationIsOem(scanFile)) {
8682                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
8683            } else {
8684                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_OEM;
8685            }
8686
8687            if (ps != null && !ps.codePath.equals(scanFile)) {
8688                // The path has changed from what was last scanned...  check the
8689                // version of the new path against what we have stored to determine
8690                // what to do.
8691                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8692                if (pkg.mVersionCode <= ps.versionCode) {
8693                    // The system package has been updated and the code path does not match
8694                    // Ignore entry. Skip it.
8695                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8696                            + " ignored: updated version " + ps.versionCode
8697                            + " better than this " + pkg.mVersionCode);
8698                    if (!updatedPkg.codePath.equals(scanFile)) {
8699                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8700                                + ps.name + " changing from " + updatedPkg.codePathString
8701                                + " to " + scanFile);
8702                        updatedPkg.codePath = scanFile;
8703                        updatedPkg.codePathString = scanFile.toString();
8704                        updatedPkg.resourcePath = scanFile;
8705                        updatedPkg.resourcePathString = scanFile.toString();
8706                    }
8707                    updatedPkg.pkg = pkg;
8708                    updatedPkg.versionCode = pkg.mVersionCode;
8709
8710                    // Update the disabled system child packages to point to the package too.
8711                    final int childCount = updatedPkg.childPackageNames != null
8712                            ? updatedPkg.childPackageNames.size() : 0;
8713                    for (int i = 0; i < childCount; i++) {
8714                        String childPackageName = updatedPkg.childPackageNames.get(i);
8715                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8716                                childPackageName);
8717                        if (updatedChildPkg != null) {
8718                            updatedChildPkg.pkg = pkg;
8719                            updatedChildPkg.versionCode = pkg.mVersionCode;
8720                        }
8721                    }
8722                } else {
8723                    // The current app on the system partition is better than
8724                    // what we have updated to on the data partition; switch
8725                    // back to the system partition version.
8726                    // At this point, its safely assumed that package installation for
8727                    // apps in system partition will go through. If not there won't be a working
8728                    // version of the app
8729                    // writer
8730                    synchronized (mPackages) {
8731                        // Just remove the loaded entries from package lists.
8732                        mPackages.remove(ps.name);
8733                    }
8734
8735                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8736                            + " reverting from " + ps.codePathString
8737                            + ": new version " + pkg.mVersionCode
8738                            + " better than installed " + ps.versionCode);
8739
8740                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8741                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8742                    synchronized (mInstallLock) {
8743                        args.cleanUpResourcesLI();
8744                    }
8745                    synchronized (mPackages) {
8746                        mSettings.enableSystemPackageLPw(ps.name);
8747                    }
8748                    isUpdatedPkgBetter = true;
8749                }
8750            }
8751        }
8752
8753        String resourcePath = null;
8754        String baseResourcePath = null;
8755        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
8756            if (ps != null && ps.resourcePathString != null) {
8757                resourcePath = ps.resourcePathString;
8758                baseResourcePath = ps.resourcePathString;
8759            } else {
8760                // Should not happen at all. Just log an error.
8761                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8762            }
8763        } else {
8764            resourcePath = pkg.codePath;
8765            baseResourcePath = pkg.baseCodePath;
8766        }
8767
8768        // Set application objects path explicitly.
8769        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8770        pkg.setApplicationInfoCodePath(pkg.codePath);
8771        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8772        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8773        pkg.setApplicationInfoResourcePath(resourcePath);
8774        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8775        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8776
8777        // throw an exception if we have an update to a system application, but, it's not more
8778        // recent than the package we've already scanned
8779        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
8780            // Set CPU Abis to application info.
8781            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
8782                final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, updatedPkg);
8783                derivePackageAbi(pkg, scanFile, cpuAbiOverride, false, mAppLib32InstallDir);
8784            } else {
8785                pkg.applicationInfo.primaryCpuAbi = updatedPkg.primaryCpuAbiString;
8786                pkg.applicationInfo.secondaryCpuAbi = updatedPkg.secondaryCpuAbiString;
8787            }
8788
8789            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8790                    + scanFile + " ignored: updated version " + ps.versionCode
8791                    + " better than this " + pkg.mVersionCode);
8792        }
8793
8794        if (isUpdatedPkg) {
8795            // An updated system app will not have the PARSE_IS_SYSTEM flag set
8796            // initially
8797            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
8798
8799            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
8800            // flag set initially
8801            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8802                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
8803            }
8804
8805            // An updated OEM app will not have the PARSE_IS_OEM
8806            // flag set initially
8807            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
8808                policyFlags |= PackageParser.PARSE_IS_OEM;
8809            }
8810        }
8811
8812        // Verify certificates against what was last scanned
8813        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
8814
8815        /*
8816         * A new system app appeared, but we already had a non-system one of the
8817         * same name installed earlier.
8818         */
8819        boolean shouldHideSystemApp = false;
8820        if (!isUpdatedPkg && ps != null
8821                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8822            /*
8823             * Check to make sure the signatures match first. If they don't,
8824             * wipe the installed application and its data.
8825             */
8826            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
8827                    != PackageManager.SIGNATURE_MATCH) {
8828                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
8829                        + " signatures don't match existing userdata copy; removing");
8830                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8831                        "scanPackageInternalLI")) {
8832                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8833                }
8834                ps = null;
8835            } else {
8836                /*
8837                 * If the newly-added system app is an older version than the
8838                 * already installed version, hide it. It will be scanned later
8839                 * and re-added like an update.
8840                 */
8841                if (pkg.mVersionCode <= ps.versionCode) {
8842                    shouldHideSystemApp = true;
8843                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
8844                            + " but new version " + pkg.mVersionCode + " better than installed "
8845                            + ps.versionCode + "; hiding system");
8846                } else {
8847                    /*
8848                     * The newly found system app is a newer version that the
8849                     * one previously installed. Simply remove the
8850                     * already-installed application and replace it with our own
8851                     * while keeping the application data.
8852                     */
8853                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8854                            + " reverting from " + ps.codePathString + ": new version "
8855                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
8856                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8857                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8858                    synchronized (mInstallLock) {
8859                        args.cleanUpResourcesLI();
8860                    }
8861                }
8862            }
8863        }
8864
8865        // The apk is forward locked (not public) if its code and resources
8866        // are kept in different files. (except for app in either system or
8867        // vendor path).
8868        // TODO grab this value from PackageSettings
8869        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8870            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8871                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8872            }
8873        }
8874
8875        final int userId = ((user == null) ? 0 : user.getIdentifier());
8876        if (ps != null && ps.getInstantApp(userId)) {
8877            scanFlags |= SCAN_AS_INSTANT_APP;
8878        }
8879        if (ps != null && ps.getVirtulalPreload(userId)) {
8880            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
8881        }
8882
8883        // Note that we invoke the following method only if we are about to unpack an application
8884        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8885                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8886
8887        /*
8888         * If the system app should be overridden by a previously installed
8889         * data, hide the system app now and let the /data/app scan pick it up
8890         * again.
8891         */
8892        if (shouldHideSystemApp) {
8893            synchronized (mPackages) {
8894                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8895            }
8896        }
8897
8898        return scannedPkg;
8899    }
8900
8901    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8902        // Derive the new package synthetic package name
8903        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8904                + pkg.staticSharedLibVersion);
8905    }
8906
8907    private static String fixProcessName(String defProcessName,
8908            String processName) {
8909        if (processName == null) {
8910            return defProcessName;
8911        }
8912        return processName;
8913    }
8914
8915    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8916            throws PackageManagerException {
8917        if (pkgSetting.signatures.mSignatures != null) {
8918            // Already existing package. Make sure signatures match
8919            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8920                    == PackageManager.SIGNATURE_MATCH;
8921            if (!match) {
8922                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
8923                        == PackageManager.SIGNATURE_MATCH;
8924            }
8925            if (!match) {
8926                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
8927                        == PackageManager.SIGNATURE_MATCH;
8928            }
8929            if (!match) {
8930                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
8931                        + pkg.packageName + " signatures do not match the "
8932                        + "previously installed version; ignoring!");
8933            }
8934        }
8935
8936        // Check for shared user signatures
8937        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8938            // Already existing package. Make sure signatures match
8939            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8940                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8941            if (!match) {
8942                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8943                        == PackageManager.SIGNATURE_MATCH;
8944            }
8945            if (!match) {
8946                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8947                        == PackageManager.SIGNATURE_MATCH;
8948            }
8949            if (!match) {
8950                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8951                        "Package " + pkg.packageName
8952                        + " has no signatures that match those in shared user "
8953                        + pkgSetting.sharedUser.name + "; ignoring!");
8954            }
8955        }
8956    }
8957
8958    /**
8959     * Enforces that only the system UID or root's UID can call a method exposed
8960     * via Binder.
8961     *
8962     * @param message used as message if SecurityException is thrown
8963     * @throws SecurityException if the caller is not system or root
8964     */
8965    private static final void enforceSystemOrRoot(String message) {
8966        final int uid = Binder.getCallingUid();
8967        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8968            throw new SecurityException(message);
8969        }
8970    }
8971
8972    @Override
8973    public void performFstrimIfNeeded() {
8974        enforceSystemOrRoot("Only the system can request fstrim");
8975
8976        // Before everything else, see whether we need to fstrim.
8977        try {
8978            IStorageManager sm = PackageHelper.getStorageManager();
8979            if (sm != null) {
8980                boolean doTrim = false;
8981                final long interval = android.provider.Settings.Global.getLong(
8982                        mContext.getContentResolver(),
8983                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8984                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8985                if (interval > 0) {
8986                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8987                    if (timeSinceLast > interval) {
8988                        doTrim = true;
8989                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8990                                + "; running immediately");
8991                    }
8992                }
8993                if (doTrim) {
8994                    final boolean dexOptDialogShown;
8995                    synchronized (mPackages) {
8996                        dexOptDialogShown = mDexOptDialogShown;
8997                    }
8998                    if (!isFirstBoot() && dexOptDialogShown) {
8999                        try {
9000                            ActivityManager.getService().showBootMessage(
9001                                    mContext.getResources().getString(
9002                                            R.string.android_upgrading_fstrim), true);
9003                        } catch (RemoteException e) {
9004                        }
9005                    }
9006                    sm.runMaintenance();
9007                }
9008            } else {
9009                Slog.e(TAG, "storageManager service unavailable!");
9010            }
9011        } catch (RemoteException e) {
9012            // Can't happen; StorageManagerService is local
9013        }
9014    }
9015
9016    @Override
9017    public void updatePackagesIfNeeded() {
9018        enforceSystemOrRoot("Only the system can request package update");
9019
9020        // We need to re-extract after an OTA.
9021        boolean causeUpgrade = isUpgrade();
9022
9023        // First boot or factory reset.
9024        // Note: we also handle devices that are upgrading to N right now as if it is their
9025        //       first boot, as they do not have profile data.
9026        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9027
9028        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9029        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9030
9031        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9032            return;
9033        }
9034
9035        List<PackageParser.Package> pkgs;
9036        synchronized (mPackages) {
9037            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9038        }
9039
9040        final long startTime = System.nanoTime();
9041        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9042                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9043                    false /* bootComplete */);
9044
9045        final int elapsedTimeSeconds =
9046                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9047
9048        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9049        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9050        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9051        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9052        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9053    }
9054
9055    /*
9056     * Return the prebuilt profile path given a package base code path.
9057     */
9058    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9059        return pkg.baseCodePath + ".prof";
9060    }
9061
9062    /**
9063     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9064     * containing statistics about the invocation. The array consists of three elements,
9065     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9066     * and {@code numberOfPackagesFailed}.
9067     */
9068    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9069            final String compilerFilter, boolean bootComplete) {
9070
9071        int numberOfPackagesVisited = 0;
9072        int numberOfPackagesOptimized = 0;
9073        int numberOfPackagesSkipped = 0;
9074        int numberOfPackagesFailed = 0;
9075        final int numberOfPackagesToDexopt = pkgs.size();
9076
9077        for (PackageParser.Package pkg : pkgs) {
9078            numberOfPackagesVisited++;
9079
9080            boolean useProfileForDexopt = false;
9081
9082            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9083                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9084                // that are already compiled.
9085                File profileFile = new File(getPrebuildProfilePath(pkg));
9086                // Copy profile if it exists.
9087                if (profileFile.exists()) {
9088                    try {
9089                        // We could also do this lazily before calling dexopt in
9090                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9091                        // is that we don't have a good way to say "do this only once".
9092                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9093                                pkg.applicationInfo.uid, pkg.packageName)) {
9094                            Log.e(TAG, "Installer failed to copy system profile!");
9095                        } else {
9096                            // Disabled as this causes speed-profile compilation during first boot
9097                            // even if things are already compiled.
9098                            // useProfileForDexopt = true;
9099                        }
9100                    } catch (Exception e) {
9101                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9102                                e);
9103                    }
9104                } else {
9105                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9106                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
9107                    // minimize the number off apps being speed-profile compiled during first boot.
9108                    // The other paths will not change the filter.
9109                    if (disabledPs != null && disabledPs.pkg.isStub) {
9110                        // The package is the stub one, remove the stub suffix to get the normal
9111                        // package and APK names.
9112                        String systemProfilePath =
9113                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
9114                        File systemProfile = new File(systemProfilePath);
9115                        // Use the profile for compilation if there exists one for the same package
9116                        // in the system partition.
9117                        useProfileForDexopt = systemProfile.exists();
9118                    }
9119                }
9120            }
9121
9122            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9123                if (DEBUG_DEXOPT) {
9124                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9125                }
9126                numberOfPackagesSkipped++;
9127                continue;
9128            }
9129
9130            if (DEBUG_DEXOPT) {
9131                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9132                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9133            }
9134
9135            if (showDialog) {
9136                try {
9137                    ActivityManager.getService().showBootMessage(
9138                            mContext.getResources().getString(R.string.android_upgrading_apk,
9139                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9140                } catch (RemoteException e) {
9141                }
9142                synchronized (mPackages) {
9143                    mDexOptDialogShown = true;
9144                }
9145            }
9146
9147            String pkgCompilerFilter = compilerFilter;
9148            if (useProfileForDexopt) {
9149                // Use background dexopt mode to try and use the profile. Note that this does not
9150                // guarantee usage of the profile.
9151                pkgCompilerFilter =
9152                        PackageManagerServiceCompilerMapping.getCompilerFilterForReason(
9153                                PackageManagerService.REASON_BACKGROUND_DEXOPT);
9154            }
9155
9156            // checkProfiles is false to avoid merging profiles during boot which
9157            // might interfere with background compilation (b/28612421).
9158            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9159            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9160            // trade-off worth doing to save boot time work.
9161            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9162            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9163                    pkg.packageName,
9164                    pkgCompilerFilter,
9165                    dexoptFlags));
9166
9167            switch (primaryDexOptStaus) {
9168                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9169                    numberOfPackagesOptimized++;
9170                    break;
9171                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9172                    numberOfPackagesSkipped++;
9173                    break;
9174                case PackageDexOptimizer.DEX_OPT_FAILED:
9175                    numberOfPackagesFailed++;
9176                    break;
9177                default:
9178                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9179                    break;
9180            }
9181        }
9182
9183        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9184                numberOfPackagesFailed };
9185    }
9186
9187    @Override
9188    public void notifyPackageUse(String packageName, int reason) {
9189        synchronized (mPackages) {
9190            final int callingUid = Binder.getCallingUid();
9191            final int callingUserId = UserHandle.getUserId(callingUid);
9192            if (getInstantAppPackageName(callingUid) != null) {
9193                if (!isCallerSameApp(packageName, callingUid)) {
9194                    return;
9195                }
9196            } else {
9197                if (isInstantApp(packageName, callingUserId)) {
9198                    return;
9199                }
9200            }
9201            notifyPackageUseLocked(packageName, reason);
9202        }
9203    }
9204
9205    private void notifyPackageUseLocked(String packageName, int reason) {
9206        final PackageParser.Package p = mPackages.get(packageName);
9207        if (p == null) {
9208            return;
9209        }
9210        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9211    }
9212
9213    @Override
9214    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9215            List<String> classPaths, String loaderIsa) {
9216        int userId = UserHandle.getCallingUserId();
9217        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9218        if (ai == null) {
9219            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9220                + loadingPackageName + ", user=" + userId);
9221            return;
9222        }
9223        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9224    }
9225
9226    @Override
9227    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9228            IDexModuleRegisterCallback callback) {
9229        int userId = UserHandle.getCallingUserId();
9230        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9231        DexManager.RegisterDexModuleResult result;
9232        if (ai == null) {
9233            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9234                     " calling user. package=" + packageName + ", user=" + userId);
9235            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9236        } else {
9237            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9238        }
9239
9240        if (callback != null) {
9241            mHandler.post(() -> {
9242                try {
9243                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9244                } catch (RemoteException e) {
9245                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9246                }
9247            });
9248        }
9249    }
9250
9251    /**
9252     * Ask the package manager to perform a dex-opt with the given compiler filter.
9253     *
9254     * Note: exposed only for the shell command to allow moving packages explicitly to a
9255     *       definite state.
9256     */
9257    @Override
9258    public boolean performDexOptMode(String packageName,
9259            boolean checkProfiles, String targetCompilerFilter, boolean force,
9260            boolean bootComplete, String splitName) {
9261        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9262                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9263                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9264        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9265                splitName, flags));
9266    }
9267
9268    /**
9269     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9270     * secondary dex files belonging to the given package.
9271     *
9272     * Note: exposed only for the shell command to allow moving packages explicitly to a
9273     *       definite state.
9274     */
9275    @Override
9276    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9277            boolean force) {
9278        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9279                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9280                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9281                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9282        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9283    }
9284
9285    /*package*/ boolean performDexOpt(DexoptOptions options) {
9286        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9287            return false;
9288        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9289            return false;
9290        }
9291
9292        if (options.isDexoptOnlySecondaryDex()) {
9293            return mDexManager.dexoptSecondaryDex(options);
9294        } else {
9295            int dexoptStatus = performDexOptWithStatus(options);
9296            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9297        }
9298    }
9299
9300    /**
9301     * Perform dexopt on the given package and return one of following result:
9302     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9303     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9304     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9305     */
9306    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9307        return performDexOptTraced(options);
9308    }
9309
9310    private int performDexOptTraced(DexoptOptions options) {
9311        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9312        try {
9313            return performDexOptInternal(options);
9314        } finally {
9315            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9316        }
9317    }
9318
9319    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9320    // if the package can now be considered up to date for the given filter.
9321    private int performDexOptInternal(DexoptOptions options) {
9322        PackageParser.Package p;
9323        synchronized (mPackages) {
9324            p = mPackages.get(options.getPackageName());
9325            if (p == null) {
9326                // Package could not be found. Report failure.
9327                return PackageDexOptimizer.DEX_OPT_FAILED;
9328            }
9329            mPackageUsage.maybeWriteAsync(mPackages);
9330            mCompilerStats.maybeWriteAsync();
9331        }
9332        long callingId = Binder.clearCallingIdentity();
9333        try {
9334            synchronized (mInstallLock) {
9335                return performDexOptInternalWithDependenciesLI(p, options);
9336            }
9337        } finally {
9338            Binder.restoreCallingIdentity(callingId);
9339        }
9340    }
9341
9342    public ArraySet<String> getOptimizablePackages() {
9343        ArraySet<String> pkgs = new ArraySet<String>();
9344        synchronized (mPackages) {
9345            for (PackageParser.Package p : mPackages.values()) {
9346                if (PackageDexOptimizer.canOptimizePackage(p)) {
9347                    pkgs.add(p.packageName);
9348                }
9349            }
9350        }
9351        return pkgs;
9352    }
9353
9354    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9355            DexoptOptions options) {
9356        // Select the dex optimizer based on the force parameter.
9357        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9358        //       allocate an object here.
9359        PackageDexOptimizer pdo = options.isForce()
9360                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9361                : mPackageDexOptimizer;
9362
9363        // Dexopt all dependencies first. Note: we ignore the return value and march on
9364        // on errors.
9365        // Note that we are going to call performDexOpt on those libraries as many times as
9366        // they are referenced in packages. When we do a batch of performDexOpt (for example
9367        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9368        // and the first package that uses the library will dexopt it. The
9369        // others will see that the compiled code for the library is up to date.
9370        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9371        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9372        if (!deps.isEmpty()) {
9373            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9374                    options.getCompilerFilter(), options.getSplitName(),
9375                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9376            for (PackageParser.Package depPackage : deps) {
9377                // TODO: Analyze and investigate if we (should) profile libraries.
9378                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9379                        getOrCreateCompilerPackageStats(depPackage),
9380                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9381            }
9382        }
9383        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9384                getOrCreateCompilerPackageStats(p),
9385                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9386    }
9387
9388    /**
9389     * Reconcile the information we have about the secondary dex files belonging to
9390     * {@code packagName} and the actual dex files. For all dex files that were
9391     * deleted, update the internal records and delete the generated oat files.
9392     */
9393    @Override
9394    public void reconcileSecondaryDexFiles(String packageName) {
9395        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9396            return;
9397        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9398            return;
9399        }
9400        mDexManager.reconcileSecondaryDexFiles(packageName);
9401    }
9402
9403    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9404    // a reference there.
9405    /*package*/ DexManager getDexManager() {
9406        return mDexManager;
9407    }
9408
9409    /**
9410     * Execute the background dexopt job immediately.
9411     */
9412    @Override
9413    public boolean runBackgroundDexoptJob() {
9414        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9415            return false;
9416        }
9417        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9418    }
9419
9420    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9421        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9422                || p.usesStaticLibraries != null) {
9423            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9424            Set<String> collectedNames = new HashSet<>();
9425            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9426
9427            retValue.remove(p);
9428
9429            return retValue;
9430        } else {
9431            return Collections.emptyList();
9432        }
9433    }
9434
9435    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9436            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9437        if (!collectedNames.contains(p.packageName)) {
9438            collectedNames.add(p.packageName);
9439            collected.add(p);
9440
9441            if (p.usesLibraries != null) {
9442                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9443                        null, collected, collectedNames);
9444            }
9445            if (p.usesOptionalLibraries != null) {
9446                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9447                        null, collected, collectedNames);
9448            }
9449            if (p.usesStaticLibraries != null) {
9450                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9451                        p.usesStaticLibrariesVersions, collected, collectedNames);
9452            }
9453        }
9454    }
9455
9456    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9457            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9458        final int libNameCount = libs.size();
9459        for (int i = 0; i < libNameCount; i++) {
9460            String libName = libs.get(i);
9461            int version = (versions != null && versions.length == libNameCount)
9462                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9463            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9464            if (libPkg != null) {
9465                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9466            }
9467        }
9468    }
9469
9470    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9471        synchronized (mPackages) {
9472            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9473            if (libEntry != null) {
9474                return mPackages.get(libEntry.apk);
9475            }
9476            return null;
9477        }
9478    }
9479
9480    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9481        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9482        if (versionedLib == null) {
9483            return null;
9484        }
9485        return versionedLib.get(version);
9486    }
9487
9488    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9489        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9490                pkg.staticSharedLibName);
9491        if (versionedLib == null) {
9492            return null;
9493        }
9494        int previousLibVersion = -1;
9495        final int versionCount = versionedLib.size();
9496        for (int i = 0; i < versionCount; i++) {
9497            final int libVersion = versionedLib.keyAt(i);
9498            if (libVersion < pkg.staticSharedLibVersion) {
9499                previousLibVersion = Math.max(previousLibVersion, libVersion);
9500            }
9501        }
9502        if (previousLibVersion >= 0) {
9503            return versionedLib.get(previousLibVersion);
9504        }
9505        return null;
9506    }
9507
9508    public void shutdown() {
9509        mPackageUsage.writeNow(mPackages);
9510        mCompilerStats.writeNow();
9511        mDexManager.writePackageDexUsageNow();
9512    }
9513
9514    @Override
9515    public void dumpProfiles(String packageName) {
9516        PackageParser.Package pkg;
9517        synchronized (mPackages) {
9518            pkg = mPackages.get(packageName);
9519            if (pkg == null) {
9520                throw new IllegalArgumentException("Unknown package: " + packageName);
9521            }
9522        }
9523        /* Only the shell, root, or the app user should be able to dump profiles. */
9524        int callingUid = Binder.getCallingUid();
9525        if (callingUid != Process.SHELL_UID &&
9526            callingUid != Process.ROOT_UID &&
9527            callingUid != pkg.applicationInfo.uid) {
9528            throw new SecurityException("dumpProfiles");
9529        }
9530
9531        synchronized (mInstallLock) {
9532            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9533            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9534            try {
9535                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9536                String codePaths = TextUtils.join(";", allCodePaths);
9537                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9538            } catch (InstallerException e) {
9539                Slog.w(TAG, "Failed to dump profiles", e);
9540            }
9541            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9542        }
9543    }
9544
9545    @Override
9546    public void forceDexOpt(String packageName) {
9547        enforceSystemOrRoot("forceDexOpt");
9548
9549        PackageParser.Package pkg;
9550        synchronized (mPackages) {
9551            pkg = mPackages.get(packageName);
9552            if (pkg == null) {
9553                throw new IllegalArgumentException("Unknown package: " + packageName);
9554            }
9555        }
9556
9557        synchronized (mInstallLock) {
9558            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9559
9560            // Whoever is calling forceDexOpt wants a compiled package.
9561            // Don't use profiles since that may cause compilation to be skipped.
9562            final int res = performDexOptInternalWithDependenciesLI(
9563                    pkg,
9564                    new DexoptOptions(packageName,
9565                            getDefaultCompilerFilter(),
9566                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9567
9568            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9569            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9570                throw new IllegalStateException("Failed to dexopt: " + res);
9571            }
9572        }
9573    }
9574
9575    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9576        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9577            Slog.w(TAG, "Unable to update from " + oldPkg.name
9578                    + " to " + newPkg.packageName
9579                    + ": old package not in system partition");
9580            return false;
9581        } else if (mPackages.get(oldPkg.name) != null) {
9582            Slog.w(TAG, "Unable to update from " + oldPkg.name
9583                    + " to " + newPkg.packageName
9584                    + ": old package still exists");
9585            return false;
9586        }
9587        return true;
9588    }
9589
9590    void removeCodePathLI(File codePath) {
9591        if (codePath.isDirectory()) {
9592            try {
9593                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9594            } catch (InstallerException e) {
9595                Slog.w(TAG, "Failed to remove code path", e);
9596            }
9597        } else {
9598            codePath.delete();
9599        }
9600    }
9601
9602    private int[] resolveUserIds(int userId) {
9603        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9604    }
9605
9606    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9607        if (pkg == null) {
9608            Slog.wtf(TAG, "Package was null!", new Throwable());
9609            return;
9610        }
9611        clearAppDataLeafLIF(pkg, userId, flags);
9612        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9613        for (int i = 0; i < childCount; i++) {
9614            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9615        }
9616    }
9617
9618    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9619        final PackageSetting ps;
9620        synchronized (mPackages) {
9621            ps = mSettings.mPackages.get(pkg.packageName);
9622        }
9623        for (int realUserId : resolveUserIds(userId)) {
9624            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9625            try {
9626                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9627                        ceDataInode);
9628            } catch (InstallerException e) {
9629                Slog.w(TAG, String.valueOf(e));
9630            }
9631        }
9632    }
9633
9634    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9635        if (pkg == null) {
9636            Slog.wtf(TAG, "Package was null!", new Throwable());
9637            return;
9638        }
9639        destroyAppDataLeafLIF(pkg, userId, flags);
9640        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9641        for (int i = 0; i < childCount; i++) {
9642            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9643        }
9644    }
9645
9646    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9647        final PackageSetting ps;
9648        synchronized (mPackages) {
9649            ps = mSettings.mPackages.get(pkg.packageName);
9650        }
9651        for (int realUserId : resolveUserIds(userId)) {
9652            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9653            try {
9654                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9655                        ceDataInode);
9656            } catch (InstallerException e) {
9657                Slog.w(TAG, String.valueOf(e));
9658            }
9659            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9660        }
9661    }
9662
9663    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9664        if (pkg == null) {
9665            Slog.wtf(TAG, "Package was null!", new Throwable());
9666            return;
9667        }
9668        destroyAppProfilesLeafLIF(pkg);
9669        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9670        for (int i = 0; i < childCount; i++) {
9671            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9672        }
9673    }
9674
9675    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9676        try {
9677            mInstaller.destroyAppProfiles(pkg.packageName);
9678        } catch (InstallerException e) {
9679            Slog.w(TAG, String.valueOf(e));
9680        }
9681    }
9682
9683    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9684        if (pkg == null) {
9685            Slog.wtf(TAG, "Package was null!", new Throwable());
9686            return;
9687        }
9688        clearAppProfilesLeafLIF(pkg);
9689        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9690        for (int i = 0; i < childCount; i++) {
9691            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9692        }
9693    }
9694
9695    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9696        try {
9697            mInstaller.clearAppProfiles(pkg.packageName);
9698        } catch (InstallerException e) {
9699            Slog.w(TAG, String.valueOf(e));
9700        }
9701    }
9702
9703    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9704            long lastUpdateTime) {
9705        // Set parent install/update time
9706        PackageSetting ps = (PackageSetting) pkg.mExtras;
9707        if (ps != null) {
9708            ps.firstInstallTime = firstInstallTime;
9709            ps.lastUpdateTime = lastUpdateTime;
9710        }
9711        // Set children install/update time
9712        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9713        for (int i = 0; i < childCount; i++) {
9714            PackageParser.Package childPkg = pkg.childPackages.get(i);
9715            ps = (PackageSetting) childPkg.mExtras;
9716            if (ps != null) {
9717                ps.firstInstallTime = firstInstallTime;
9718                ps.lastUpdateTime = lastUpdateTime;
9719            }
9720        }
9721    }
9722
9723    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
9724            PackageParser.Package changingLib) {
9725        if (file.path != null) {
9726            usesLibraryFiles.add(file.path);
9727            return;
9728        }
9729        PackageParser.Package p = mPackages.get(file.apk);
9730        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9731            // If we are doing this while in the middle of updating a library apk,
9732            // then we need to make sure to use that new apk for determining the
9733            // dependencies here.  (We haven't yet finished committing the new apk
9734            // to the package manager state.)
9735            if (p == null || p.packageName.equals(changingLib.packageName)) {
9736                p = changingLib;
9737            }
9738        }
9739        if (p != null) {
9740            usesLibraryFiles.addAll(p.getAllCodePaths());
9741            if (p.usesLibraryFiles != null) {
9742                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9743            }
9744        }
9745    }
9746
9747    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9748            PackageParser.Package changingLib) throws PackageManagerException {
9749        if (pkg == null) {
9750            return;
9751        }
9752        ArraySet<String> usesLibraryFiles = null;
9753        if (pkg.usesLibraries != null) {
9754            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9755                    null, null, pkg.packageName, changingLib, true,
9756                    pkg.applicationInfo.targetSdkVersion, null);
9757        }
9758        if (pkg.usesStaticLibraries != null) {
9759            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9760                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9761                    pkg.packageName, changingLib, true,
9762                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9763        }
9764        if (pkg.usesOptionalLibraries != null) {
9765            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9766                    null, null, pkg.packageName, changingLib, false,
9767                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9768        }
9769        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9770            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9771        } else {
9772            pkg.usesLibraryFiles = null;
9773        }
9774    }
9775
9776    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9777            @Nullable int[] requiredVersions, @Nullable String[][] requiredCertDigests,
9778            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9779            boolean required, int targetSdk, @Nullable ArraySet<String> outUsedLibraries)
9780            throws PackageManagerException {
9781        final int libCount = requestedLibraries.size();
9782        for (int i = 0; i < libCount; i++) {
9783            final String libName = requestedLibraries.get(i);
9784            final int libVersion = requiredVersions != null ? requiredVersions[i]
9785                    : SharedLibraryInfo.VERSION_UNDEFINED;
9786            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9787            if (libEntry == null) {
9788                if (required) {
9789                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9790                            "Package " + packageName + " requires unavailable shared library "
9791                                    + libName + "; failing!");
9792                } else if (DEBUG_SHARED_LIBRARIES) {
9793                    Slog.i(TAG, "Package " + packageName
9794                            + " desires unavailable shared library "
9795                            + libName + "; ignoring!");
9796                }
9797            } else {
9798                if (requiredVersions != null && requiredCertDigests != null) {
9799                    if (libEntry.info.getVersion() != requiredVersions[i]) {
9800                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9801                            "Package " + packageName + " requires unavailable static shared"
9802                                    + " library " + libName + " version "
9803                                    + libEntry.info.getVersion() + "; failing!");
9804                    }
9805
9806                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9807                    if (libPkg == null) {
9808                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9809                                "Package " + packageName + " requires unavailable static shared"
9810                                        + " library; failing!");
9811                    }
9812
9813                    final String[] expectedCertDigests = requiredCertDigests[i];
9814                    // For apps targeting O MR1 we require explicit enumeration of all certs.
9815                    final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9816                            ? PackageUtils.computeSignaturesSha256Digests(libPkg.mSignatures)
9817                            : PackageUtils.computeSignaturesSha256Digests(
9818                                    new Signature[]{libPkg.mSignatures[0]});
9819
9820                    // Take a shortcut if sizes don't match. Note that if an app doesn't
9821                    // target O we don't parse the "additional-certificate" tags similarly
9822                    // how we only consider all certs only for apps targeting O (see above).
9823                    // Therefore, the size check is safe to make.
9824                    if (expectedCertDigests.length != libCertDigests.length) {
9825                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9826                                "Package " + packageName + " requires differently signed" +
9827                                        " static sDexLoadReporter.java:45.19hared library; failing!");
9828                    }
9829
9830                    // Use a predictable order as signature order may vary
9831                    Arrays.sort(libCertDigests);
9832                    Arrays.sort(expectedCertDigests);
9833
9834                    final int certCount = libCertDigests.length;
9835                    for (int j = 0; j < certCount; j++) {
9836                        if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9837                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9838                                    "Package " + packageName + " requires differently signed" +
9839                                            " static shared library; failing!");
9840                        }
9841                    }
9842                }
9843
9844                if (outUsedLibraries == null) {
9845                    outUsedLibraries = new ArraySet<>();
9846                }
9847                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9848            }
9849        }
9850        return outUsedLibraries;
9851    }
9852
9853    private static boolean hasString(List<String> list, List<String> which) {
9854        if (list == null) {
9855            return false;
9856        }
9857        for (int i=list.size()-1; i>=0; i--) {
9858            for (int j=which.size()-1; j>=0; j--) {
9859                if (which.get(j).equals(list.get(i))) {
9860                    return true;
9861                }
9862            }
9863        }
9864        return false;
9865    }
9866
9867    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9868            PackageParser.Package changingPkg) {
9869        ArrayList<PackageParser.Package> res = null;
9870        for (PackageParser.Package pkg : mPackages.values()) {
9871            if (changingPkg != null
9872                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9873                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9874                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9875                            changingPkg.staticSharedLibName)) {
9876                return null;
9877            }
9878            if (res == null) {
9879                res = new ArrayList<>();
9880            }
9881            res.add(pkg);
9882            try {
9883                updateSharedLibrariesLPr(pkg, changingPkg);
9884            } catch (PackageManagerException e) {
9885                // If a system app update or an app and a required lib missing we
9886                // delete the package and for updated system apps keep the data as
9887                // it is better for the user to reinstall than to be in an limbo
9888                // state. Also libs disappearing under an app should never happen
9889                // - just in case.
9890                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
9891                    final int flags = pkg.isUpdatedSystemApp()
9892                            ? PackageManager.DELETE_KEEP_DATA : 0;
9893                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9894                            flags , null, true, null);
9895                }
9896                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9897            }
9898        }
9899        return res;
9900    }
9901
9902    /**
9903     * Derive the value of the {@code cpuAbiOverride} based on the provided
9904     * value and an optional stored value from the package settings.
9905     */
9906    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
9907        String cpuAbiOverride = null;
9908
9909        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
9910            cpuAbiOverride = null;
9911        } else if (abiOverride != null) {
9912            cpuAbiOverride = abiOverride;
9913        } else if (settings != null) {
9914            cpuAbiOverride = settings.cpuAbiOverrideString;
9915        }
9916
9917        return cpuAbiOverride;
9918    }
9919
9920    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9921            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9922                    throws PackageManagerException {
9923        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9924        // If the package has children and this is the first dive in the function
9925        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9926        // whether all packages (parent and children) would be successfully scanned
9927        // before the actual scan since scanning mutates internal state and we want
9928        // to atomically install the package and its children.
9929        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9930            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9931                scanFlags |= SCAN_CHECK_ONLY;
9932            }
9933        } else {
9934            scanFlags &= ~SCAN_CHECK_ONLY;
9935        }
9936
9937        final PackageParser.Package scannedPkg;
9938        try {
9939            // Scan the parent
9940            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
9941            // Scan the children
9942            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9943            for (int i = 0; i < childCount; i++) {
9944                PackageParser.Package childPkg = pkg.childPackages.get(i);
9945                scanPackageLI(childPkg, policyFlags,
9946                        scanFlags, currentTime, user);
9947            }
9948        } finally {
9949            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9950        }
9951
9952        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9953            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
9954        }
9955
9956        return scannedPkg;
9957    }
9958
9959    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
9960            int scanFlags, long currentTime, @Nullable UserHandle user)
9961                    throws PackageManagerException {
9962        boolean success = false;
9963        try {
9964            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
9965                    currentTime, user);
9966            success = true;
9967            return res;
9968        } finally {
9969            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9970                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9971                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9972                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9973                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9974            }
9975        }
9976    }
9977
9978    /**
9979     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9980     */
9981    private static boolean apkHasCode(String fileName) {
9982        StrictJarFile jarFile = null;
9983        try {
9984            jarFile = new StrictJarFile(fileName,
9985                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9986            return jarFile.findEntry("classes.dex") != null;
9987        } catch (IOException ignore) {
9988        } finally {
9989            try {
9990                if (jarFile != null) {
9991                    jarFile.close();
9992                }
9993            } catch (IOException ignore) {}
9994        }
9995        return false;
9996    }
9997
9998    /**
9999     * Enforces code policy for the package. This ensures that if an APK has
10000     * declared hasCode="true" in its manifest that the APK actually contains
10001     * code.
10002     *
10003     * @throws PackageManagerException If bytecode could not be found when it should exist
10004     */
10005    private static void assertCodePolicy(PackageParser.Package pkg)
10006            throws PackageManagerException {
10007        final boolean shouldHaveCode =
10008                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10009        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10010            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10011                    "Package " + pkg.baseCodePath + " code is missing");
10012        }
10013
10014        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10015            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10016                final boolean splitShouldHaveCode =
10017                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10018                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10019                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10020                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10021                }
10022            }
10023        }
10024    }
10025
10026    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10027            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10028                    throws PackageManagerException {
10029        if (DEBUG_PACKAGE_SCANNING) {
10030            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10031                Log.d(TAG, "Scanning package " + pkg.packageName);
10032        }
10033
10034        applyPolicy(pkg, policyFlags);
10035
10036        assertPackageIsValid(pkg, policyFlags, scanFlags);
10037
10038        if (Build.IS_DEBUGGABLE &&
10039                pkg.isPrivilegedApp() &&
10040                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10041            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10042        }
10043
10044        // Initialize package source and resource directories
10045        final File scanFile = new File(pkg.codePath);
10046        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10047        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10048
10049        SharedUserSetting suid = null;
10050        PackageSetting pkgSetting = null;
10051
10052        // Getting the package setting may have a side-effect, so if we
10053        // are only checking if scan would succeed, stash a copy of the
10054        // old setting to restore at the end.
10055        PackageSetting nonMutatedPs = null;
10056
10057        // We keep references to the derived CPU Abis from settings in oder to reuse
10058        // them in the case where we're not upgrading or booting for the first time.
10059        String primaryCpuAbiFromSettings = null;
10060        String secondaryCpuAbiFromSettings = null;
10061
10062        // writer
10063        synchronized (mPackages) {
10064            if (pkg.mSharedUserId != null) {
10065                // SIDE EFFECTS; may potentially allocate a new shared user
10066                suid = mSettings.getSharedUserLPw(
10067                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10068                if (DEBUG_PACKAGE_SCANNING) {
10069                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10070                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10071                                + "): packages=" + suid.packages);
10072                }
10073            }
10074
10075            // Check if we are renaming from an original package name.
10076            PackageSetting origPackage = null;
10077            String realName = null;
10078            if (pkg.mOriginalPackages != null) {
10079                // This package may need to be renamed to a previously
10080                // installed name.  Let's check on that...
10081                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10082                if (pkg.mOriginalPackages.contains(renamed)) {
10083                    // This package had originally been installed as the
10084                    // original name, and we have already taken care of
10085                    // transitioning to the new one.  Just update the new
10086                    // one to continue using the old name.
10087                    realName = pkg.mRealPackage;
10088                    if (!pkg.packageName.equals(renamed)) {
10089                        // Callers into this function may have already taken
10090                        // care of renaming the package; only do it here if
10091                        // it is not already done.
10092                        pkg.setPackageName(renamed);
10093                    }
10094                } else {
10095                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10096                        if ((origPackage = mSettings.getPackageLPr(
10097                                pkg.mOriginalPackages.get(i))) != null) {
10098                            // We do have the package already installed under its
10099                            // original name...  should we use it?
10100                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10101                                // New package is not compatible with original.
10102                                origPackage = null;
10103                                continue;
10104                            } else if (origPackage.sharedUser != null) {
10105                                // Make sure uid is compatible between packages.
10106                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10107                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10108                                            + " to " + pkg.packageName + ": old uid "
10109                                            + origPackage.sharedUser.name
10110                                            + " differs from " + pkg.mSharedUserId);
10111                                    origPackage = null;
10112                                    continue;
10113                                }
10114                                // TODO: Add case when shared user id is added [b/28144775]
10115                            } else {
10116                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10117                                        + pkg.packageName + " to old name " + origPackage.name);
10118                            }
10119                            break;
10120                        }
10121                    }
10122                }
10123            }
10124
10125            if (mTransferedPackages.contains(pkg.packageName)) {
10126                Slog.w(TAG, "Package " + pkg.packageName
10127                        + " was transferred to another, but its .apk remains");
10128            }
10129
10130            // See comments in nonMutatedPs declaration
10131            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10132                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10133                if (foundPs != null) {
10134                    nonMutatedPs = new PackageSetting(foundPs);
10135                }
10136            }
10137
10138            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10139                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10140                if (foundPs != null) {
10141                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10142                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10143                }
10144            }
10145
10146            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10147            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10148                PackageManagerService.reportSettingsProblem(Log.WARN,
10149                        "Package " + pkg.packageName + " shared user changed from "
10150                                + (pkgSetting.sharedUser != null
10151                                        ? pkgSetting.sharedUser.name : "<nothing>")
10152                                + " to "
10153                                + (suid != null ? suid.name : "<nothing>")
10154                                + "; replacing with new");
10155                pkgSetting = null;
10156            }
10157            final PackageSetting oldPkgSetting =
10158                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10159            final PackageSetting disabledPkgSetting =
10160                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10161
10162            String[] usesStaticLibraries = null;
10163            if (pkg.usesStaticLibraries != null) {
10164                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10165                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10166            }
10167
10168            if (pkgSetting == null) {
10169                final String parentPackageName = (pkg.parentPackage != null)
10170                        ? pkg.parentPackage.packageName : null;
10171                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10172                final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10173                // REMOVE SharedUserSetting from method; update in a separate call
10174                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10175                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10176                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10177                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10178                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10179                        true /*allowInstall*/, instantApp, virtualPreload,
10180                        parentPackageName, pkg.getChildPackageNames(),
10181                        UserManagerService.getInstance(), usesStaticLibraries,
10182                        pkg.usesStaticLibrariesVersions);
10183                // SIDE EFFECTS; updates system state; move elsewhere
10184                if (origPackage != null) {
10185                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10186                }
10187                mSettings.addUserToSettingLPw(pkgSetting);
10188            } else {
10189                // REMOVE SharedUserSetting from method; update in a separate call.
10190                //
10191                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10192                // secondaryCpuAbi are not known at this point so we always update them
10193                // to null here, only to reset them at a later point.
10194                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10195                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10196                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10197                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10198                        UserManagerService.getInstance(), usesStaticLibraries,
10199                        pkg.usesStaticLibrariesVersions);
10200            }
10201            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10202            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10203
10204            // SIDE EFFECTS; modifies system state; move elsewhere
10205            if (pkgSetting.origPackage != null) {
10206                // If we are first transitioning from an original package,
10207                // fix up the new package's name now.  We need to do this after
10208                // looking up the package under its new name, so getPackageLP
10209                // can take care of fiddling things correctly.
10210                pkg.setPackageName(origPackage.name);
10211
10212                // File a report about this.
10213                String msg = "New package " + pkgSetting.realName
10214                        + " renamed to replace old package " + pkgSetting.name;
10215                reportSettingsProblem(Log.WARN, msg);
10216
10217                // Make a note of it.
10218                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10219                    mTransferedPackages.add(origPackage.name);
10220                }
10221
10222                // No longer need to retain this.
10223                pkgSetting.origPackage = null;
10224            }
10225
10226            // SIDE EFFECTS; modifies system state; move elsewhere
10227            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10228                // Make a note of it.
10229                mTransferedPackages.add(pkg.packageName);
10230            }
10231
10232            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10233                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10234            }
10235
10236            if ((scanFlags & SCAN_BOOTING) == 0
10237                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10238                // Check all shared libraries and map to their actual file path.
10239                // We only do this here for apps not on a system dir, because those
10240                // are the only ones that can fail an install due to this.  We
10241                // will take care of the system apps by updating all of their
10242                // library paths after the scan is done. Also during the initial
10243                // scan don't update any libs as we do this wholesale after all
10244                // apps are scanned to avoid dependency based scanning.
10245                updateSharedLibrariesLPr(pkg, null);
10246            }
10247
10248            if (mFoundPolicyFile) {
10249                SELinuxMMAC.assignSeInfoValue(pkg);
10250            }
10251            pkg.applicationInfo.uid = pkgSetting.appId;
10252            pkg.mExtras = pkgSetting;
10253
10254
10255            // Static shared libs have same package with different versions where
10256            // we internally use a synthetic package name to allow multiple versions
10257            // of the same package, therefore we need to compare signatures against
10258            // the package setting for the latest library version.
10259            PackageSetting signatureCheckPs = pkgSetting;
10260            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10261                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10262                if (libraryEntry != null) {
10263                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10264                }
10265            }
10266
10267            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10268                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10269                    // We just determined the app is signed correctly, so bring
10270                    // over the latest parsed certs.
10271                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10272                } else {
10273                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10274                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10275                                "Package " + pkg.packageName + " upgrade keys do not match the "
10276                                + "previously installed version");
10277                    } else {
10278                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10279                        String msg = "System package " + pkg.packageName
10280                                + " signature changed; retaining data.";
10281                        reportSettingsProblem(Log.WARN, msg);
10282                    }
10283                }
10284            } else {
10285                try {
10286                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10287                    verifySignaturesLP(signatureCheckPs, pkg);
10288                    // We just determined the app is signed correctly, so bring
10289                    // over the latest parsed certs.
10290                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10291                } catch (PackageManagerException e) {
10292                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10293                        throw e;
10294                    }
10295                    // The signature has changed, but this package is in the system
10296                    // image...  let's recover!
10297                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10298                    // However...  if this package is part of a shared user, but it
10299                    // doesn't match the signature of the shared user, let's fail.
10300                    // What this means is that you can't change the signatures
10301                    // associated with an overall shared user, which doesn't seem all
10302                    // that unreasonable.
10303                    if (signatureCheckPs.sharedUser != null) {
10304                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10305                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10306                            throw new PackageManagerException(
10307                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10308                                    "Signature mismatch for shared user: "
10309                                            + pkgSetting.sharedUser);
10310                        }
10311                    }
10312                    // File a report about this.
10313                    String msg = "System package " + pkg.packageName
10314                            + " signature changed; retaining data.";
10315                    reportSettingsProblem(Log.WARN, msg);
10316                }
10317            }
10318
10319            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10320                // This package wants to adopt ownership of permissions from
10321                // another package.
10322                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10323                    final String origName = pkg.mAdoptPermissions.get(i);
10324                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10325                    if (orig != null) {
10326                        if (verifyPackageUpdateLPr(orig, pkg)) {
10327                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10328                                    + pkg.packageName);
10329                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10330                            mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10331                        }
10332                    }
10333                }
10334            }
10335        }
10336
10337        pkg.applicationInfo.processName = fixProcessName(
10338                pkg.applicationInfo.packageName,
10339                pkg.applicationInfo.processName);
10340
10341        if (pkg != mPlatformPackage) {
10342            // Get all of our default paths setup
10343            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10344        }
10345
10346        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10347
10348        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10349            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10350                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10351                final boolean extractNativeLibs = !pkg.isLibrary();
10352                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10353                        mAppLib32InstallDir);
10354                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10355
10356                // Some system apps still use directory structure for native libraries
10357                // in which case we might end up not detecting abi solely based on apk
10358                // structure. Try to detect abi based on directory structure.
10359                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10360                        pkg.applicationInfo.primaryCpuAbi == null) {
10361                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10362                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10363                }
10364            } else {
10365                // This is not a first boot or an upgrade, don't bother deriving the
10366                // ABI during the scan. Instead, trust the value that was stored in the
10367                // package setting.
10368                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10369                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10370
10371                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10372
10373                if (DEBUG_ABI_SELECTION) {
10374                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10375                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10376                        pkg.applicationInfo.secondaryCpuAbi);
10377                }
10378            }
10379        } else {
10380            if ((scanFlags & SCAN_MOVE) != 0) {
10381                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10382                // but we already have this packages package info in the PackageSetting. We just
10383                // use that and derive the native library path based on the new codepath.
10384                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10385                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10386            }
10387
10388            // Set native library paths again. For moves, the path will be updated based on the
10389            // ABIs we've determined above. For non-moves, the path will be updated based on the
10390            // ABIs we determined during compilation, but the path will depend on the final
10391            // package path (after the rename away from the stage path).
10392            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10393        }
10394
10395        // This is a special case for the "system" package, where the ABI is
10396        // dictated by the zygote configuration (and init.rc). We should keep track
10397        // of this ABI so that we can deal with "normal" applications that run under
10398        // the same UID correctly.
10399        if (mPlatformPackage == pkg) {
10400            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10401                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10402        }
10403
10404        // If there's a mismatch between the abi-override in the package setting
10405        // and the abiOverride specified for the install. Warn about this because we
10406        // would've already compiled the app without taking the package setting into
10407        // account.
10408        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10409            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10410                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10411                        " for package " + pkg.packageName);
10412            }
10413        }
10414
10415        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10416        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10417        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10418
10419        // Copy the derived override back to the parsed package, so that we can
10420        // update the package settings accordingly.
10421        pkg.cpuAbiOverride = cpuAbiOverride;
10422
10423        if (DEBUG_ABI_SELECTION) {
10424            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10425                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10426                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10427        }
10428
10429        // Push the derived path down into PackageSettings so we know what to
10430        // clean up at uninstall time.
10431        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10432
10433        if (DEBUG_ABI_SELECTION) {
10434            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10435                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10436                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10437        }
10438
10439        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10440        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10441            // We don't do this here during boot because we can do it all
10442            // at once after scanning all existing packages.
10443            //
10444            // We also do this *before* we perform dexopt on this package, so that
10445            // we can avoid redundant dexopts, and also to make sure we've got the
10446            // code and package path correct.
10447            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10448        }
10449
10450        if (mFactoryTest && pkg.requestedPermissions.contains(
10451                android.Manifest.permission.FACTORY_TEST)) {
10452            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10453        }
10454
10455        if (isSystemApp(pkg)) {
10456            pkgSetting.isOrphaned = true;
10457        }
10458
10459        // Take care of first install / last update times.
10460        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10461        if (currentTime != 0) {
10462            if (pkgSetting.firstInstallTime == 0) {
10463                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10464            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10465                pkgSetting.lastUpdateTime = currentTime;
10466            }
10467        } else if (pkgSetting.firstInstallTime == 0) {
10468            // We need *something*.  Take time time stamp of the file.
10469            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10470        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10471            if (scanFileTime != pkgSetting.timeStamp) {
10472                // A package on the system image has changed; consider this
10473                // to be an update.
10474                pkgSetting.lastUpdateTime = scanFileTime;
10475            }
10476        }
10477        pkgSetting.setTimeStamp(scanFileTime);
10478
10479        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10480            if (nonMutatedPs != null) {
10481                synchronized (mPackages) {
10482                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10483                }
10484            }
10485        } else {
10486            final int userId = user == null ? 0 : user.getIdentifier();
10487            // Modify state for the given package setting
10488            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10489                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10490            if (pkgSetting.getInstantApp(userId)) {
10491                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10492            }
10493        }
10494        return pkg;
10495    }
10496
10497    /**
10498     * Applies policy to the parsed package based upon the given policy flags.
10499     * Ensures the package is in a good state.
10500     * <p>
10501     * Implementation detail: This method must NOT have any side effect. It would
10502     * ideally be static, but, it requires locks to read system state.
10503     */
10504    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10505        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10506            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10507            if (pkg.applicationInfo.isDirectBootAware()) {
10508                // we're direct boot aware; set for all components
10509                for (PackageParser.Service s : pkg.services) {
10510                    s.info.encryptionAware = s.info.directBootAware = true;
10511                }
10512                for (PackageParser.Provider p : pkg.providers) {
10513                    p.info.encryptionAware = p.info.directBootAware = true;
10514                }
10515                for (PackageParser.Activity a : pkg.activities) {
10516                    a.info.encryptionAware = a.info.directBootAware = true;
10517                }
10518                for (PackageParser.Activity r : pkg.receivers) {
10519                    r.info.encryptionAware = r.info.directBootAware = true;
10520                }
10521            }
10522            if (compressedFileExists(pkg.codePath)) {
10523                pkg.isStub = true;
10524            }
10525        } else {
10526            // Only allow system apps to be flagged as core apps.
10527            pkg.coreApp = false;
10528            // clear flags not applicable to regular apps
10529            pkg.applicationInfo.privateFlags &=
10530                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10531            pkg.applicationInfo.privateFlags &=
10532                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10533        }
10534        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10535
10536        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10537            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10538        }
10539
10540        if ((policyFlags&PackageParser.PARSE_IS_OEM) != 0) {
10541            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10542        }
10543
10544        if (!isSystemApp(pkg)) {
10545            // Only system apps can use these features.
10546            pkg.mOriginalPackages = null;
10547            pkg.mRealPackage = null;
10548            pkg.mAdoptPermissions = null;
10549        }
10550    }
10551
10552    /**
10553     * Asserts the parsed package is valid according to the given policy. If the
10554     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10555     * <p>
10556     * Implementation detail: This method must NOT have any side effects. It would
10557     * ideally be static, but, it requires locks to read system state.
10558     *
10559     * @throws PackageManagerException If the package fails any of the validation checks
10560     */
10561    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10562            throws PackageManagerException {
10563        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10564            assertCodePolicy(pkg);
10565        }
10566
10567        if (pkg.applicationInfo.getCodePath() == null ||
10568                pkg.applicationInfo.getResourcePath() == null) {
10569            // Bail out. The resource and code paths haven't been set.
10570            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10571                    "Code and resource paths haven't been set correctly");
10572        }
10573
10574        // Make sure we're not adding any bogus keyset info
10575        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10576        ksms.assertScannedPackageValid(pkg);
10577
10578        synchronized (mPackages) {
10579            // The special "android" package can only be defined once
10580            if (pkg.packageName.equals("android")) {
10581                if (mAndroidApplication != null) {
10582                    Slog.w(TAG, "*************************************************");
10583                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10584                    Slog.w(TAG, " codePath=" + pkg.codePath);
10585                    Slog.w(TAG, "*************************************************");
10586                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10587                            "Core android package being redefined.  Skipping.");
10588                }
10589            }
10590
10591            // A package name must be unique; don't allow duplicates
10592            if (mPackages.containsKey(pkg.packageName)) {
10593                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10594                        "Application package " + pkg.packageName
10595                        + " already installed.  Skipping duplicate.");
10596            }
10597
10598            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10599                // Static libs have a synthetic package name containing the version
10600                // but we still want the base name to be unique.
10601                if (mPackages.containsKey(pkg.manifestPackageName)) {
10602                    throw new PackageManagerException(
10603                            "Duplicate static shared lib provider package");
10604                }
10605
10606                // Static shared libraries should have at least O target SDK
10607                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10608                    throw new PackageManagerException(
10609                            "Packages declaring static-shared libs must target O SDK or higher");
10610                }
10611
10612                // Package declaring static a shared lib cannot be instant apps
10613                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10614                    throw new PackageManagerException(
10615                            "Packages declaring static-shared libs cannot be instant apps");
10616                }
10617
10618                // Package declaring static a shared lib cannot be renamed since the package
10619                // name is synthetic and apps can't code around package manager internals.
10620                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10621                    throw new PackageManagerException(
10622                            "Packages declaring static-shared libs cannot be renamed");
10623                }
10624
10625                // Package declaring static a shared lib cannot declare child packages
10626                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10627                    throw new PackageManagerException(
10628                            "Packages declaring static-shared libs cannot have child packages");
10629                }
10630
10631                // Package declaring static a shared lib cannot declare dynamic libs
10632                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10633                    throw new PackageManagerException(
10634                            "Packages declaring static-shared libs cannot declare dynamic libs");
10635                }
10636
10637                // Package declaring static a shared lib cannot declare shared users
10638                if (pkg.mSharedUserId != null) {
10639                    throw new PackageManagerException(
10640                            "Packages declaring static-shared libs cannot declare shared users");
10641                }
10642
10643                // Static shared libs cannot declare activities
10644                if (!pkg.activities.isEmpty()) {
10645                    throw new PackageManagerException(
10646                            "Static shared libs cannot declare activities");
10647                }
10648
10649                // Static shared libs cannot declare services
10650                if (!pkg.services.isEmpty()) {
10651                    throw new PackageManagerException(
10652                            "Static shared libs cannot declare services");
10653                }
10654
10655                // Static shared libs cannot declare providers
10656                if (!pkg.providers.isEmpty()) {
10657                    throw new PackageManagerException(
10658                            "Static shared libs cannot declare content providers");
10659                }
10660
10661                // Static shared libs cannot declare receivers
10662                if (!pkg.receivers.isEmpty()) {
10663                    throw new PackageManagerException(
10664                            "Static shared libs cannot declare broadcast receivers");
10665                }
10666
10667                // Static shared libs cannot declare permission groups
10668                if (!pkg.permissionGroups.isEmpty()) {
10669                    throw new PackageManagerException(
10670                            "Static shared libs cannot declare permission groups");
10671                }
10672
10673                // Static shared libs cannot declare permissions
10674                if (!pkg.permissions.isEmpty()) {
10675                    throw new PackageManagerException(
10676                            "Static shared libs cannot declare permissions");
10677                }
10678
10679                // Static shared libs cannot declare protected broadcasts
10680                if (pkg.protectedBroadcasts != null) {
10681                    throw new PackageManagerException(
10682                            "Static shared libs cannot declare protected broadcasts");
10683                }
10684
10685                // Static shared libs cannot be overlay targets
10686                if (pkg.mOverlayTarget != null) {
10687                    throw new PackageManagerException(
10688                            "Static shared libs cannot be overlay targets");
10689                }
10690
10691                // The version codes must be ordered as lib versions
10692                int minVersionCode = Integer.MIN_VALUE;
10693                int maxVersionCode = Integer.MAX_VALUE;
10694
10695                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10696                        pkg.staticSharedLibName);
10697                if (versionedLib != null) {
10698                    final int versionCount = versionedLib.size();
10699                    for (int i = 0; i < versionCount; i++) {
10700                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10701                        final int libVersionCode = libInfo.getDeclaringPackage()
10702                                .getVersionCode();
10703                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10704                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10705                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10706                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10707                        } else {
10708                            minVersionCode = maxVersionCode = libVersionCode;
10709                            break;
10710                        }
10711                    }
10712                }
10713                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10714                    throw new PackageManagerException("Static shared"
10715                            + " lib version codes must be ordered as lib versions");
10716                }
10717            }
10718
10719            // Only privileged apps and updated privileged apps can add child packages.
10720            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10721                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10722                    throw new PackageManagerException("Only privileged apps can add child "
10723                            + "packages. Ignoring package " + pkg.packageName);
10724                }
10725                final int childCount = pkg.childPackages.size();
10726                for (int i = 0; i < childCount; i++) {
10727                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10728                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10729                            childPkg.packageName)) {
10730                        throw new PackageManagerException("Can't override child of "
10731                                + "another disabled app. Ignoring package " + pkg.packageName);
10732                    }
10733                }
10734            }
10735
10736            // If we're only installing presumed-existing packages, require that the
10737            // scanned APK is both already known and at the path previously established
10738            // for it.  Previously unknown packages we pick up normally, but if we have an
10739            // a priori expectation about this package's install presence, enforce it.
10740            // With a singular exception for new system packages. When an OTA contains
10741            // a new system package, we allow the codepath to change from a system location
10742            // to the user-installed location. If we don't allow this change, any newer,
10743            // user-installed version of the application will be ignored.
10744            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10745                if (mExpectingBetter.containsKey(pkg.packageName)) {
10746                    logCriticalInfo(Log.WARN,
10747                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10748                } else {
10749                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10750                    if (known != null) {
10751                        if (DEBUG_PACKAGE_SCANNING) {
10752                            Log.d(TAG, "Examining " + pkg.codePath
10753                                    + " and requiring known paths " + known.codePathString
10754                                    + " & " + known.resourcePathString);
10755                        }
10756                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10757                                || !pkg.applicationInfo.getResourcePath().equals(
10758                                        known.resourcePathString)) {
10759                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10760                                    "Application package " + pkg.packageName
10761                                    + " found at " + pkg.applicationInfo.getCodePath()
10762                                    + " but expected at " + known.codePathString
10763                                    + "; ignoring.");
10764                        }
10765                    } else {
10766                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10767                                "Application package " + pkg.packageName
10768                                + " not found; ignoring.");
10769                    }
10770                }
10771            }
10772
10773            // Verify that this new package doesn't have any content providers
10774            // that conflict with existing packages.  Only do this if the
10775            // package isn't already installed, since we don't want to break
10776            // things that are installed.
10777            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10778                final int N = pkg.providers.size();
10779                int i;
10780                for (i=0; i<N; i++) {
10781                    PackageParser.Provider p = pkg.providers.get(i);
10782                    if (p.info.authority != null) {
10783                        String names[] = p.info.authority.split(";");
10784                        for (int j = 0; j < names.length; j++) {
10785                            if (mProvidersByAuthority.containsKey(names[j])) {
10786                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10787                                final String otherPackageName =
10788                                        ((other != null && other.getComponentName() != null) ?
10789                                                other.getComponentName().getPackageName() : "?");
10790                                throw new PackageManagerException(
10791                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10792                                        "Can't install because provider name " + names[j]
10793                                                + " (in package " + pkg.applicationInfo.packageName
10794                                                + ") is already used by " + otherPackageName);
10795                            }
10796                        }
10797                    }
10798                }
10799            }
10800        }
10801    }
10802
10803    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10804            int type, String declaringPackageName, int declaringVersionCode) {
10805        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10806        if (versionedLib == null) {
10807            versionedLib = new SparseArray<>();
10808            mSharedLibraries.put(name, versionedLib);
10809            if (type == SharedLibraryInfo.TYPE_STATIC) {
10810                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10811            }
10812        } else if (versionedLib.indexOfKey(version) >= 0) {
10813            return false;
10814        }
10815        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10816                version, type, declaringPackageName, declaringVersionCode);
10817        versionedLib.put(version, libEntry);
10818        return true;
10819    }
10820
10821    private boolean removeSharedLibraryLPw(String name, int version) {
10822        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10823        if (versionedLib == null) {
10824            return false;
10825        }
10826        final int libIdx = versionedLib.indexOfKey(version);
10827        if (libIdx < 0) {
10828            return false;
10829        }
10830        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10831        versionedLib.remove(version);
10832        if (versionedLib.size() <= 0) {
10833            mSharedLibraries.remove(name);
10834            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10835                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10836                        .getPackageName());
10837            }
10838        }
10839        return true;
10840    }
10841
10842    /**
10843     * Adds a scanned package to the system. When this method is finished, the package will
10844     * be available for query, resolution, etc...
10845     */
10846    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10847            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
10848        final String pkgName = pkg.packageName;
10849        if (mCustomResolverComponentName != null &&
10850                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10851            setUpCustomResolverActivity(pkg);
10852        }
10853
10854        if (pkg.packageName.equals("android")) {
10855            synchronized (mPackages) {
10856                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10857                    // Set up information for our fall-back user intent resolution activity.
10858                    mPlatformPackage = pkg;
10859                    pkg.mVersionCode = mSdkVersion;
10860                    mAndroidApplication = pkg.applicationInfo;
10861                    if (!mResolverReplaced) {
10862                        mResolveActivity.applicationInfo = mAndroidApplication;
10863                        mResolveActivity.name = ResolverActivity.class.getName();
10864                        mResolveActivity.packageName = mAndroidApplication.packageName;
10865                        mResolveActivity.processName = "system:ui";
10866                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10867                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10868                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10869                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10870                        mResolveActivity.exported = true;
10871                        mResolveActivity.enabled = true;
10872                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10873                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10874                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10875                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10876                                | ActivityInfo.CONFIG_ORIENTATION
10877                                | ActivityInfo.CONFIG_KEYBOARD
10878                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10879                        mResolveInfo.activityInfo = mResolveActivity;
10880                        mResolveInfo.priority = 0;
10881                        mResolveInfo.preferredOrder = 0;
10882                        mResolveInfo.match = 0;
10883                        mResolveComponentName = new ComponentName(
10884                                mAndroidApplication.packageName, mResolveActivity.name);
10885                    }
10886                }
10887            }
10888        }
10889
10890        ArrayList<PackageParser.Package> clientLibPkgs = null;
10891        // writer
10892        synchronized (mPackages) {
10893            boolean hasStaticSharedLibs = false;
10894
10895            // Any app can add new static shared libraries
10896            if (pkg.staticSharedLibName != null) {
10897                // Static shared libs don't allow renaming as they have synthetic package
10898                // names to allow install of multiple versions, so use name from manifest.
10899                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10900                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10901                        pkg.manifestPackageName, pkg.mVersionCode)) {
10902                    hasStaticSharedLibs = true;
10903                } else {
10904                    Slog.w(TAG, "Package " + pkg.packageName + " library "
10905                                + pkg.staticSharedLibName + " already exists; skipping");
10906                }
10907                // Static shared libs cannot be updated once installed since they
10908                // use synthetic package name which includes the version code, so
10909                // not need to update other packages's shared lib dependencies.
10910            }
10911
10912            if (!hasStaticSharedLibs
10913                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10914                // Only system apps can add new dynamic shared libraries.
10915                if (pkg.libraryNames != null) {
10916                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
10917                        String name = pkg.libraryNames.get(i);
10918                        boolean allowed = false;
10919                        if (pkg.isUpdatedSystemApp()) {
10920                            // New library entries can only be added through the
10921                            // system image.  This is important to get rid of a lot
10922                            // of nasty edge cases: for example if we allowed a non-
10923                            // system update of the app to add a library, then uninstalling
10924                            // the update would make the library go away, and assumptions
10925                            // we made such as through app install filtering would now
10926                            // have allowed apps on the device which aren't compatible
10927                            // with it.  Better to just have the restriction here, be
10928                            // conservative, and create many fewer cases that can negatively
10929                            // impact the user experience.
10930                            final PackageSetting sysPs = mSettings
10931                                    .getDisabledSystemPkgLPr(pkg.packageName);
10932                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
10933                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
10934                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
10935                                        allowed = true;
10936                                        break;
10937                                    }
10938                                }
10939                            }
10940                        } else {
10941                            allowed = true;
10942                        }
10943                        if (allowed) {
10944                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
10945                                    SharedLibraryInfo.VERSION_UNDEFINED,
10946                                    SharedLibraryInfo.TYPE_DYNAMIC,
10947                                    pkg.packageName, pkg.mVersionCode)) {
10948                                Slog.w(TAG, "Package " + pkg.packageName + " library "
10949                                        + name + " already exists; skipping");
10950                            }
10951                        } else {
10952                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
10953                                    + name + " that is not declared on system image; skipping");
10954                        }
10955                    }
10956
10957                    if ((scanFlags & SCAN_BOOTING) == 0) {
10958                        // If we are not booting, we need to update any applications
10959                        // that are clients of our shared library.  If we are booting,
10960                        // this will all be done once the scan is complete.
10961                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10962                    }
10963                }
10964            }
10965        }
10966
10967        if ((scanFlags & SCAN_BOOTING) != 0) {
10968            // No apps can run during boot scan, so they don't need to be frozen
10969        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10970            // Caller asked to not kill app, so it's probably not frozen
10971        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10972            // Caller asked us to ignore frozen check for some reason; they
10973            // probably didn't know the package name
10974        } else {
10975            // We're doing major surgery on this package, so it better be frozen
10976            // right now to keep it from launching
10977            checkPackageFrozen(pkgName);
10978        }
10979
10980        // Also need to kill any apps that are dependent on the library.
10981        if (clientLibPkgs != null) {
10982            for (int i=0; i<clientLibPkgs.size(); i++) {
10983                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10984                killApplication(clientPkg.applicationInfo.packageName,
10985                        clientPkg.applicationInfo.uid, "update lib");
10986            }
10987        }
10988
10989        // writer
10990        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10991
10992        synchronized (mPackages) {
10993            // We don't expect installation to fail beyond this point
10994
10995            // Add the new setting to mSettings
10996            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10997            // Add the new setting to mPackages
10998            mPackages.put(pkg.applicationInfo.packageName, pkg);
10999            // Make sure we don't accidentally delete its data.
11000            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11001            while (iter.hasNext()) {
11002                PackageCleanItem item = iter.next();
11003                if (pkgName.equals(item.packageName)) {
11004                    iter.remove();
11005                }
11006            }
11007
11008            // Add the package's KeySets to the global KeySetManagerService
11009            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11010            ksms.addScannedPackageLPw(pkg);
11011
11012            int N = pkg.providers.size();
11013            StringBuilder r = null;
11014            int i;
11015            for (i=0; i<N; i++) {
11016                PackageParser.Provider p = pkg.providers.get(i);
11017                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11018                        p.info.processName);
11019                mProviders.addProvider(p);
11020                p.syncable = p.info.isSyncable;
11021                if (p.info.authority != null) {
11022                    String names[] = p.info.authority.split(";");
11023                    p.info.authority = null;
11024                    for (int j = 0; j < names.length; j++) {
11025                        if (j == 1 && p.syncable) {
11026                            // We only want the first authority for a provider to possibly be
11027                            // syncable, so if we already added this provider using a different
11028                            // authority clear the syncable flag. We copy the provider before
11029                            // changing it because the mProviders object contains a reference
11030                            // to a provider that we don't want to change.
11031                            // Only do this for the second authority since the resulting provider
11032                            // object can be the same for all future authorities for this provider.
11033                            p = new PackageParser.Provider(p);
11034                            p.syncable = false;
11035                        }
11036                        if (!mProvidersByAuthority.containsKey(names[j])) {
11037                            mProvidersByAuthority.put(names[j], p);
11038                            if (p.info.authority == null) {
11039                                p.info.authority = names[j];
11040                            } else {
11041                                p.info.authority = p.info.authority + ";" + names[j];
11042                            }
11043                            if (DEBUG_PACKAGE_SCANNING) {
11044                                if (chatty)
11045                                    Log.d(TAG, "Registered content provider: " + names[j]
11046                                            + ", className = " + p.info.name + ", isSyncable = "
11047                                            + p.info.isSyncable);
11048                            }
11049                        } else {
11050                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11051                            Slog.w(TAG, "Skipping provider name " + names[j] +
11052                                    " (in package " + pkg.applicationInfo.packageName +
11053                                    "): name already used by "
11054                                    + ((other != null && other.getComponentName() != null)
11055                                            ? other.getComponentName().getPackageName() : "?"));
11056                        }
11057                    }
11058                }
11059                if (chatty) {
11060                    if (r == null) {
11061                        r = new StringBuilder(256);
11062                    } else {
11063                        r.append(' ');
11064                    }
11065                    r.append(p.info.name);
11066                }
11067            }
11068            if (r != null) {
11069                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11070            }
11071
11072            N = pkg.services.size();
11073            r = null;
11074            for (i=0; i<N; i++) {
11075                PackageParser.Service s = pkg.services.get(i);
11076                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11077                        s.info.processName);
11078                mServices.addService(s);
11079                if (chatty) {
11080                    if (r == null) {
11081                        r = new StringBuilder(256);
11082                    } else {
11083                        r.append(' ');
11084                    }
11085                    r.append(s.info.name);
11086                }
11087            }
11088            if (r != null) {
11089                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11090            }
11091
11092            N = pkg.receivers.size();
11093            r = null;
11094            for (i=0; i<N; i++) {
11095                PackageParser.Activity a = pkg.receivers.get(i);
11096                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11097                        a.info.processName);
11098                mReceivers.addActivity(a, "receiver");
11099                if (chatty) {
11100                    if (r == null) {
11101                        r = new StringBuilder(256);
11102                    } else {
11103                        r.append(' ');
11104                    }
11105                    r.append(a.info.name);
11106                }
11107            }
11108            if (r != null) {
11109                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11110            }
11111
11112            N = pkg.activities.size();
11113            r = null;
11114            for (i=0; i<N; i++) {
11115                PackageParser.Activity a = pkg.activities.get(i);
11116                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11117                        a.info.processName);
11118                mActivities.addActivity(a, "activity");
11119                if (chatty) {
11120                    if (r == null) {
11121                        r = new StringBuilder(256);
11122                    } else {
11123                        r.append(' ');
11124                    }
11125                    r.append(a.info.name);
11126                }
11127            }
11128            if (r != null) {
11129                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11130            }
11131
11132            N = pkg.permissionGroups.size();
11133            r = null;
11134            for (i=0; i<N; i++) {
11135                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11136                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11137                final String curPackageName = cur == null ? null : cur.info.packageName;
11138                // Dont allow ephemeral apps to define new permission groups.
11139                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11140                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11141                            + pg.info.packageName
11142                            + " ignored: instant apps cannot define new permission groups.");
11143                    continue;
11144                }
11145                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11146                if (cur == null || isPackageUpdate) {
11147                    mPermissionGroups.put(pg.info.name, pg);
11148                    if (chatty) {
11149                        if (r == null) {
11150                            r = new StringBuilder(256);
11151                        } else {
11152                            r.append(' ');
11153                        }
11154                        if (isPackageUpdate) {
11155                            r.append("UPD:");
11156                        }
11157                        r.append(pg.info.name);
11158                    }
11159                } else {
11160                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11161                            + pg.info.packageName + " ignored: original from "
11162                            + cur.info.packageName);
11163                    if (chatty) {
11164                        if (r == null) {
11165                            r = new StringBuilder(256);
11166                        } else {
11167                            r.append(' ');
11168                        }
11169                        r.append("DUP:");
11170                        r.append(pg.info.name);
11171                    }
11172                }
11173            }
11174            if (r != null) {
11175                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11176            }
11177
11178
11179            // Dont allow ephemeral apps to define new permissions.
11180            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11181                Slog.w(TAG, "Permissions from package " + pkg.packageName
11182                        + " ignored: instant apps cannot define new permissions.");
11183            } else {
11184                mPermissionManager.addAllPermissions(pkg, chatty);
11185            }
11186
11187            N = pkg.instrumentation.size();
11188            r = null;
11189            for (i=0; i<N; i++) {
11190                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11191                a.info.packageName = pkg.applicationInfo.packageName;
11192                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11193                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11194                a.info.splitNames = pkg.splitNames;
11195                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11196                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11197                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11198                a.info.dataDir = pkg.applicationInfo.dataDir;
11199                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11200                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11201                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11202                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11203                mInstrumentation.put(a.getComponentName(), a);
11204                if (chatty) {
11205                    if (r == null) {
11206                        r = new StringBuilder(256);
11207                    } else {
11208                        r.append(' ');
11209                    }
11210                    r.append(a.info.name);
11211                }
11212            }
11213            if (r != null) {
11214                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11215            }
11216
11217            if (pkg.protectedBroadcasts != null) {
11218                N = pkg.protectedBroadcasts.size();
11219                synchronized (mProtectedBroadcasts) {
11220                    for (i = 0; i < N; i++) {
11221                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11222                    }
11223                }
11224            }
11225        }
11226
11227        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11228    }
11229
11230    /**
11231     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11232     * is derived purely on the basis of the contents of {@code scanFile} and
11233     * {@code cpuAbiOverride}.
11234     *
11235     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11236     */
11237    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11238                                 String cpuAbiOverride, boolean extractLibs,
11239                                 File appLib32InstallDir)
11240            throws PackageManagerException {
11241        // Give ourselves some initial paths; we'll come back for another
11242        // pass once we've determined ABI below.
11243        setNativeLibraryPaths(pkg, appLib32InstallDir);
11244
11245        // We would never need to extract libs for forward-locked and external packages,
11246        // since the container service will do it for us. We shouldn't attempt to
11247        // extract libs from system app when it was not updated.
11248        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11249                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11250            extractLibs = false;
11251        }
11252
11253        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11254        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11255
11256        NativeLibraryHelper.Handle handle = null;
11257        try {
11258            handle = NativeLibraryHelper.Handle.create(pkg);
11259            // TODO(multiArch): This can be null for apps that didn't go through the
11260            // usual installation process. We can calculate it again, like we
11261            // do during install time.
11262            //
11263            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11264            // unnecessary.
11265            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11266
11267            // Null out the abis so that they can be recalculated.
11268            pkg.applicationInfo.primaryCpuAbi = null;
11269            pkg.applicationInfo.secondaryCpuAbi = null;
11270            if (isMultiArch(pkg.applicationInfo)) {
11271                // Warn if we've set an abiOverride for multi-lib packages..
11272                // By definition, we need to copy both 32 and 64 bit libraries for
11273                // such packages.
11274                if (pkg.cpuAbiOverride != null
11275                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11276                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11277                }
11278
11279                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11280                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11281                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11282                    if (extractLibs) {
11283                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11284                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11285                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11286                                useIsaSpecificSubdirs);
11287                    } else {
11288                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11289                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11290                    }
11291                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11292                }
11293
11294                // Shared library native code should be in the APK zip aligned
11295                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11296                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11297                            "Shared library native lib extraction not supported");
11298                }
11299
11300                maybeThrowExceptionForMultiArchCopy(
11301                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11302
11303                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11304                    if (extractLibs) {
11305                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11306                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11307                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11308                                useIsaSpecificSubdirs);
11309                    } else {
11310                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11311                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11312                    }
11313                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11314                }
11315
11316                maybeThrowExceptionForMultiArchCopy(
11317                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11318
11319                if (abi64 >= 0) {
11320                    // Shared library native libs should be in the APK zip aligned
11321                    if (extractLibs && pkg.isLibrary()) {
11322                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11323                                "Shared library native lib extraction not supported");
11324                    }
11325                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11326                }
11327
11328                if (abi32 >= 0) {
11329                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11330                    if (abi64 >= 0) {
11331                        if (pkg.use32bitAbi) {
11332                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11333                            pkg.applicationInfo.primaryCpuAbi = abi;
11334                        } else {
11335                            pkg.applicationInfo.secondaryCpuAbi = abi;
11336                        }
11337                    } else {
11338                        pkg.applicationInfo.primaryCpuAbi = abi;
11339                    }
11340                }
11341            } else {
11342                String[] abiList = (cpuAbiOverride != null) ?
11343                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11344
11345                // Enable gross and lame hacks for apps that are built with old
11346                // SDK tools. We must scan their APKs for renderscript bitcode and
11347                // not launch them if it's present. Don't bother checking on devices
11348                // that don't have 64 bit support.
11349                boolean needsRenderScriptOverride = false;
11350                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11351                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11352                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11353                    needsRenderScriptOverride = true;
11354                }
11355
11356                final int copyRet;
11357                if (extractLibs) {
11358                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11359                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11360                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11361                } else {
11362                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11363                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11364                }
11365                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11366
11367                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11368                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11369                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11370                }
11371
11372                if (copyRet >= 0) {
11373                    // Shared libraries that have native libs must be multi-architecture
11374                    if (pkg.isLibrary()) {
11375                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11376                                "Shared library with native libs must be multiarch");
11377                    }
11378                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11379                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11380                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11381                } else if (needsRenderScriptOverride) {
11382                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11383                }
11384            }
11385        } catch (IOException ioe) {
11386            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11387        } finally {
11388            IoUtils.closeQuietly(handle);
11389        }
11390
11391        // Now that we've calculated the ABIs and determined if it's an internal app,
11392        // we will go ahead and populate the nativeLibraryPath.
11393        setNativeLibraryPaths(pkg, appLib32InstallDir);
11394    }
11395
11396    /**
11397     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11398     * i.e, so that all packages can be run inside a single process if required.
11399     *
11400     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11401     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11402     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11403     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11404     * updating a package that belongs to a shared user.
11405     *
11406     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11407     * adds unnecessary complexity.
11408     */
11409    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11410            PackageParser.Package scannedPackage) {
11411        String requiredInstructionSet = null;
11412        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11413            requiredInstructionSet = VMRuntime.getInstructionSet(
11414                     scannedPackage.applicationInfo.primaryCpuAbi);
11415        }
11416
11417        PackageSetting requirer = null;
11418        for (PackageSetting ps : packagesForUser) {
11419            // If packagesForUser contains scannedPackage, we skip it. This will happen
11420            // when scannedPackage is an update of an existing package. Without this check,
11421            // we will never be able to change the ABI of any package belonging to a shared
11422            // user, even if it's compatible with other packages.
11423            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11424                if (ps.primaryCpuAbiString == null) {
11425                    continue;
11426                }
11427
11428                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11429                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11430                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11431                    // this but there's not much we can do.
11432                    String errorMessage = "Instruction set mismatch, "
11433                            + ((requirer == null) ? "[caller]" : requirer)
11434                            + " requires " + requiredInstructionSet + " whereas " + ps
11435                            + " requires " + instructionSet;
11436                    Slog.w(TAG, errorMessage);
11437                }
11438
11439                if (requiredInstructionSet == null) {
11440                    requiredInstructionSet = instructionSet;
11441                    requirer = ps;
11442                }
11443            }
11444        }
11445
11446        if (requiredInstructionSet != null) {
11447            String adjustedAbi;
11448            if (requirer != null) {
11449                // requirer != null implies that either scannedPackage was null or that scannedPackage
11450                // did not require an ABI, in which case we have to adjust scannedPackage to match
11451                // the ABI of the set (which is the same as requirer's ABI)
11452                adjustedAbi = requirer.primaryCpuAbiString;
11453                if (scannedPackage != null) {
11454                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11455                }
11456            } else {
11457                // requirer == null implies that we're updating all ABIs in the set to
11458                // match scannedPackage.
11459                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11460            }
11461
11462            for (PackageSetting ps : packagesForUser) {
11463                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11464                    if (ps.primaryCpuAbiString != null) {
11465                        continue;
11466                    }
11467
11468                    ps.primaryCpuAbiString = adjustedAbi;
11469                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11470                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11471                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11472                        if (DEBUG_ABI_SELECTION) {
11473                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11474                                    + " (requirer="
11475                                    + (requirer != null ? requirer.pkg : "null")
11476                                    + ", scannedPackage="
11477                                    + (scannedPackage != null ? scannedPackage : "null")
11478                                    + ")");
11479                        }
11480                        try {
11481                            mInstaller.rmdex(ps.codePathString,
11482                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11483                        } catch (InstallerException ignored) {
11484                        }
11485                    }
11486                }
11487            }
11488        }
11489    }
11490
11491    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11492        synchronized (mPackages) {
11493            mResolverReplaced = true;
11494            // Set up information for custom user intent resolution activity.
11495            mResolveActivity.applicationInfo = pkg.applicationInfo;
11496            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11497            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11498            mResolveActivity.processName = pkg.applicationInfo.packageName;
11499            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11500            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11501                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11502            mResolveActivity.theme = 0;
11503            mResolveActivity.exported = true;
11504            mResolveActivity.enabled = true;
11505            mResolveInfo.activityInfo = mResolveActivity;
11506            mResolveInfo.priority = 0;
11507            mResolveInfo.preferredOrder = 0;
11508            mResolveInfo.match = 0;
11509            mResolveComponentName = mCustomResolverComponentName;
11510            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11511                    mResolveComponentName);
11512        }
11513    }
11514
11515    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11516        if (installerActivity == null) {
11517            if (DEBUG_EPHEMERAL) {
11518                Slog.d(TAG, "Clear ephemeral installer activity");
11519            }
11520            mInstantAppInstallerActivity = null;
11521            return;
11522        }
11523
11524        if (DEBUG_EPHEMERAL) {
11525            Slog.d(TAG, "Set ephemeral installer activity: "
11526                    + installerActivity.getComponentName());
11527        }
11528        // Set up information for ephemeral installer activity
11529        mInstantAppInstallerActivity = installerActivity;
11530        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11531                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11532        mInstantAppInstallerActivity.exported = true;
11533        mInstantAppInstallerActivity.enabled = true;
11534        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11535        mInstantAppInstallerInfo.priority = 0;
11536        mInstantAppInstallerInfo.preferredOrder = 1;
11537        mInstantAppInstallerInfo.isDefault = true;
11538        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11539                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11540    }
11541
11542    private static String calculateBundledApkRoot(final String codePathString) {
11543        final File codePath = new File(codePathString);
11544        final File codeRoot;
11545        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11546            codeRoot = Environment.getRootDirectory();
11547        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11548            codeRoot = Environment.getOemDirectory();
11549        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11550            codeRoot = Environment.getVendorDirectory();
11551        } else {
11552            // Unrecognized code path; take its top real segment as the apk root:
11553            // e.g. /something/app/blah.apk => /something
11554            try {
11555                File f = codePath.getCanonicalFile();
11556                File parent = f.getParentFile();    // non-null because codePath is a file
11557                File tmp;
11558                while ((tmp = parent.getParentFile()) != null) {
11559                    f = parent;
11560                    parent = tmp;
11561                }
11562                codeRoot = f;
11563                Slog.w(TAG, "Unrecognized code path "
11564                        + codePath + " - using " + codeRoot);
11565            } catch (IOException e) {
11566                // Can't canonicalize the code path -- shenanigans?
11567                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11568                return Environment.getRootDirectory().getPath();
11569            }
11570        }
11571        return codeRoot.getPath();
11572    }
11573
11574    /**
11575     * Derive and set the location of native libraries for the given package,
11576     * which varies depending on where and how the package was installed.
11577     */
11578    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11579        final ApplicationInfo info = pkg.applicationInfo;
11580        final String codePath = pkg.codePath;
11581        final File codeFile = new File(codePath);
11582        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11583        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11584
11585        info.nativeLibraryRootDir = null;
11586        info.nativeLibraryRootRequiresIsa = false;
11587        info.nativeLibraryDir = null;
11588        info.secondaryNativeLibraryDir = null;
11589
11590        if (isApkFile(codeFile)) {
11591            // Monolithic install
11592            if (bundledApp) {
11593                // If "/system/lib64/apkname" exists, assume that is the per-package
11594                // native library directory to use; otherwise use "/system/lib/apkname".
11595                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11596                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11597                        getPrimaryInstructionSet(info));
11598
11599                // This is a bundled system app so choose the path based on the ABI.
11600                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11601                // is just the default path.
11602                final String apkName = deriveCodePathName(codePath);
11603                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11604                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11605                        apkName).getAbsolutePath();
11606
11607                if (info.secondaryCpuAbi != null) {
11608                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11609                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11610                            secondaryLibDir, apkName).getAbsolutePath();
11611                }
11612            } else if (asecApp) {
11613                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11614                        .getAbsolutePath();
11615            } else {
11616                final String apkName = deriveCodePathName(codePath);
11617                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11618                        .getAbsolutePath();
11619            }
11620
11621            info.nativeLibraryRootRequiresIsa = false;
11622            info.nativeLibraryDir = info.nativeLibraryRootDir;
11623        } else {
11624            // Cluster install
11625            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11626            info.nativeLibraryRootRequiresIsa = true;
11627
11628            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11629                    getPrimaryInstructionSet(info)).getAbsolutePath();
11630
11631            if (info.secondaryCpuAbi != null) {
11632                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11633                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11634            }
11635        }
11636    }
11637
11638    /**
11639     * Calculate the abis and roots for a bundled app. These can uniquely
11640     * be determined from the contents of the system partition, i.e whether
11641     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11642     * of this information, and instead assume that the system was built
11643     * sensibly.
11644     */
11645    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11646                                           PackageSetting pkgSetting) {
11647        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11648
11649        // If "/system/lib64/apkname" exists, assume that is the per-package
11650        // native library directory to use; otherwise use "/system/lib/apkname".
11651        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11652        setBundledAppAbi(pkg, apkRoot, apkName);
11653        // pkgSetting might be null during rescan following uninstall of updates
11654        // to a bundled app, so accommodate that possibility.  The settings in
11655        // that case will be established later from the parsed package.
11656        //
11657        // If the settings aren't null, sync them up with what we've just derived.
11658        // note that apkRoot isn't stored in the package settings.
11659        if (pkgSetting != null) {
11660            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11661            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11662        }
11663    }
11664
11665    /**
11666     * Deduces the ABI of a bundled app and sets the relevant fields on the
11667     * parsed pkg object.
11668     *
11669     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11670     *        under which system libraries are installed.
11671     * @param apkName the name of the installed package.
11672     */
11673    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11674        final File codeFile = new File(pkg.codePath);
11675
11676        final boolean has64BitLibs;
11677        final boolean has32BitLibs;
11678        if (isApkFile(codeFile)) {
11679            // Monolithic install
11680            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11681            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11682        } else {
11683            // Cluster install
11684            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11685            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11686                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11687                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11688                has64BitLibs = (new File(rootDir, isa)).exists();
11689            } else {
11690                has64BitLibs = false;
11691            }
11692            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11693                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11694                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11695                has32BitLibs = (new File(rootDir, isa)).exists();
11696            } else {
11697                has32BitLibs = false;
11698            }
11699        }
11700
11701        if (has64BitLibs && !has32BitLibs) {
11702            // The package has 64 bit libs, but not 32 bit libs. Its primary
11703            // ABI should be 64 bit. We can safely assume here that the bundled
11704            // native libraries correspond to the most preferred ABI in the list.
11705
11706            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11707            pkg.applicationInfo.secondaryCpuAbi = null;
11708        } else if (has32BitLibs && !has64BitLibs) {
11709            // The package has 32 bit libs but not 64 bit libs. Its primary
11710            // ABI should be 32 bit.
11711
11712            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11713            pkg.applicationInfo.secondaryCpuAbi = null;
11714        } else if (has32BitLibs && has64BitLibs) {
11715            // The application has both 64 and 32 bit bundled libraries. We check
11716            // here that the app declares multiArch support, and warn if it doesn't.
11717            //
11718            // We will be lenient here and record both ABIs. The primary will be the
11719            // ABI that's higher on the list, i.e, a device that's configured to prefer
11720            // 64 bit apps will see a 64 bit primary ABI,
11721
11722            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11723                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11724            }
11725
11726            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11727                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11728                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11729            } else {
11730                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11731                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11732            }
11733        } else {
11734            pkg.applicationInfo.primaryCpuAbi = null;
11735            pkg.applicationInfo.secondaryCpuAbi = null;
11736        }
11737    }
11738
11739    private void killApplication(String pkgName, int appId, String reason) {
11740        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11741    }
11742
11743    private void killApplication(String pkgName, int appId, int userId, String reason) {
11744        // Request the ActivityManager to kill the process(only for existing packages)
11745        // so that we do not end up in a confused state while the user is still using the older
11746        // version of the application while the new one gets installed.
11747        final long token = Binder.clearCallingIdentity();
11748        try {
11749            IActivityManager am = ActivityManager.getService();
11750            if (am != null) {
11751                try {
11752                    am.killApplication(pkgName, appId, userId, reason);
11753                } catch (RemoteException e) {
11754                }
11755            }
11756        } finally {
11757            Binder.restoreCallingIdentity(token);
11758        }
11759    }
11760
11761    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11762        // Remove the parent package setting
11763        PackageSetting ps = (PackageSetting) pkg.mExtras;
11764        if (ps != null) {
11765            removePackageLI(ps, chatty);
11766        }
11767        // Remove the child package setting
11768        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11769        for (int i = 0; i < childCount; i++) {
11770            PackageParser.Package childPkg = pkg.childPackages.get(i);
11771            ps = (PackageSetting) childPkg.mExtras;
11772            if (ps != null) {
11773                removePackageLI(ps, chatty);
11774            }
11775        }
11776    }
11777
11778    void removePackageLI(PackageSetting ps, boolean chatty) {
11779        if (DEBUG_INSTALL) {
11780            if (chatty)
11781                Log.d(TAG, "Removing package " + ps.name);
11782        }
11783
11784        // writer
11785        synchronized (mPackages) {
11786            mPackages.remove(ps.name);
11787            final PackageParser.Package pkg = ps.pkg;
11788            if (pkg != null) {
11789                cleanPackageDataStructuresLILPw(pkg, chatty);
11790            }
11791        }
11792    }
11793
11794    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11795        if (DEBUG_INSTALL) {
11796            if (chatty)
11797                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11798        }
11799
11800        // writer
11801        synchronized (mPackages) {
11802            // Remove the parent package
11803            mPackages.remove(pkg.applicationInfo.packageName);
11804            cleanPackageDataStructuresLILPw(pkg, chatty);
11805
11806            // Remove the child packages
11807            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11808            for (int i = 0; i < childCount; i++) {
11809                PackageParser.Package childPkg = pkg.childPackages.get(i);
11810                mPackages.remove(childPkg.applicationInfo.packageName);
11811                cleanPackageDataStructuresLILPw(childPkg, chatty);
11812            }
11813        }
11814    }
11815
11816    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11817        int N = pkg.providers.size();
11818        StringBuilder r = null;
11819        int i;
11820        for (i=0; i<N; i++) {
11821            PackageParser.Provider p = pkg.providers.get(i);
11822            mProviders.removeProvider(p);
11823            if (p.info.authority == null) {
11824
11825                /* There was another ContentProvider with this authority when
11826                 * this app was installed so this authority is null,
11827                 * Ignore it as we don't have to unregister the provider.
11828                 */
11829                continue;
11830            }
11831            String names[] = p.info.authority.split(";");
11832            for (int j = 0; j < names.length; j++) {
11833                if (mProvidersByAuthority.get(names[j]) == p) {
11834                    mProvidersByAuthority.remove(names[j]);
11835                    if (DEBUG_REMOVE) {
11836                        if (chatty)
11837                            Log.d(TAG, "Unregistered content provider: " + names[j]
11838                                    + ", className = " + p.info.name + ", isSyncable = "
11839                                    + p.info.isSyncable);
11840                    }
11841                }
11842            }
11843            if (DEBUG_REMOVE && chatty) {
11844                if (r == null) {
11845                    r = new StringBuilder(256);
11846                } else {
11847                    r.append(' ');
11848                }
11849                r.append(p.info.name);
11850            }
11851        }
11852        if (r != null) {
11853            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11854        }
11855
11856        N = pkg.services.size();
11857        r = null;
11858        for (i=0; i<N; i++) {
11859            PackageParser.Service s = pkg.services.get(i);
11860            mServices.removeService(s);
11861            if (chatty) {
11862                if (r == null) {
11863                    r = new StringBuilder(256);
11864                } else {
11865                    r.append(' ');
11866                }
11867                r.append(s.info.name);
11868            }
11869        }
11870        if (r != null) {
11871            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11872        }
11873
11874        N = pkg.receivers.size();
11875        r = null;
11876        for (i=0; i<N; i++) {
11877            PackageParser.Activity a = pkg.receivers.get(i);
11878            mReceivers.removeActivity(a, "receiver");
11879            if (DEBUG_REMOVE && chatty) {
11880                if (r == null) {
11881                    r = new StringBuilder(256);
11882                } else {
11883                    r.append(' ');
11884                }
11885                r.append(a.info.name);
11886            }
11887        }
11888        if (r != null) {
11889            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11890        }
11891
11892        N = pkg.activities.size();
11893        r = null;
11894        for (i=0; i<N; i++) {
11895            PackageParser.Activity a = pkg.activities.get(i);
11896            mActivities.removeActivity(a, "activity");
11897            if (DEBUG_REMOVE && chatty) {
11898                if (r == null) {
11899                    r = new StringBuilder(256);
11900                } else {
11901                    r.append(' ');
11902                }
11903                r.append(a.info.name);
11904            }
11905        }
11906        if (r != null) {
11907            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11908        }
11909
11910        mPermissionManager.removeAllPermissions(pkg, chatty);
11911
11912        N = pkg.instrumentation.size();
11913        r = null;
11914        for (i=0; i<N; i++) {
11915            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11916            mInstrumentation.remove(a.getComponentName());
11917            if (DEBUG_REMOVE && chatty) {
11918                if (r == null) {
11919                    r = new StringBuilder(256);
11920                } else {
11921                    r.append(' ');
11922                }
11923                r.append(a.info.name);
11924            }
11925        }
11926        if (r != null) {
11927            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11928        }
11929
11930        r = null;
11931        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11932            // Only system apps can hold shared libraries.
11933            if (pkg.libraryNames != null) {
11934                for (i = 0; i < pkg.libraryNames.size(); i++) {
11935                    String name = pkg.libraryNames.get(i);
11936                    if (removeSharedLibraryLPw(name, 0)) {
11937                        if (DEBUG_REMOVE && chatty) {
11938                            if (r == null) {
11939                                r = new StringBuilder(256);
11940                            } else {
11941                                r.append(' ');
11942                            }
11943                            r.append(name);
11944                        }
11945                    }
11946                }
11947            }
11948        }
11949
11950        r = null;
11951
11952        // Any package can hold static shared libraries.
11953        if (pkg.staticSharedLibName != null) {
11954            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11955                if (DEBUG_REMOVE && chatty) {
11956                    if (r == null) {
11957                        r = new StringBuilder(256);
11958                    } else {
11959                        r.append(' ');
11960                    }
11961                    r.append(pkg.staticSharedLibName);
11962                }
11963            }
11964        }
11965
11966        if (r != null) {
11967            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11968        }
11969    }
11970
11971    public static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11972    public static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11973    public static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11974
11975    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11976        // Update the parent permissions
11977        updatePermissionsLPw(pkg.packageName, pkg, flags);
11978        // Update the child permissions
11979        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11980        for (int i = 0; i < childCount; i++) {
11981            PackageParser.Package childPkg = pkg.childPackages.get(i);
11982            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11983        }
11984    }
11985
11986    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11987            int flags) {
11988        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11989        updatePermissionsLocked(changingPkg, pkgInfo, volumeUuid, flags);
11990    }
11991
11992    private void updatePermissionsLocked(String changingPkg,
11993            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11994        // TODO: Most of the methods exposing BasePermission internals [source package name,
11995        // etc..] shouldn't be needed. Instead, when we've parsed a permission that doesn't
11996        // have package settings, we should make note of it elsewhere [map between
11997        // source package name and BasePermission] and cycle through that here. Then we
11998        // define a single method on BasePermission that takes a PackageSetting, changing
11999        // package name and a package.
12000        // NOTE: With this approach, we also don't need to tree trees differently than
12001        // normal permissions. Today, we need two separate loops because these BasePermission
12002        // objects are stored separately.
12003        // Make sure there are no dangling permission trees.
12004        flags = mPermissionManager.updatePermissionTrees(changingPkg, pkgInfo, flags);
12005
12006        // Make sure all dynamic permissions have been assigned to a package,
12007        // and make sure there are no dangling permissions.
12008        flags = mPermissionManager.updatePermissions(changingPkg, pkgInfo, flags);
12009
12010        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12011        // Now update the permissions for all packages, in particular
12012        // replace the granted permissions of the system packages.
12013        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12014            for (PackageParser.Package pkg : mPackages.values()) {
12015                if (pkg != pkgInfo) {
12016                    // Only replace for packages on requested volume
12017                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12018                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12019                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12020                    grantPermissionsLPw(pkg, replace, changingPkg);
12021                }
12022            }
12023        }
12024
12025        if (pkgInfo != null) {
12026            // Only replace for packages on requested volume
12027            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12028            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12029                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12030            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12031        }
12032        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12033    }
12034
12035    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12036            String packageOfInterest) {
12037        // IMPORTANT: There are two types of permissions: install and runtime.
12038        // Install time permissions are granted when the app is installed to
12039        // all device users and users added in the future. Runtime permissions
12040        // are granted at runtime explicitly to specific users. Normal and signature
12041        // protected permissions are install time permissions. Dangerous permissions
12042        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12043        // otherwise they are runtime permissions. This function does not manage
12044        // runtime permissions except for the case an app targeting Lollipop MR1
12045        // being upgraded to target a newer SDK, in which case dangerous permissions
12046        // are transformed from install time to runtime ones.
12047
12048        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12049        if (ps == null) {
12050            return;
12051        }
12052
12053        PermissionsState permissionsState = ps.getPermissionsState();
12054        PermissionsState origPermissions = permissionsState;
12055
12056        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12057
12058        boolean runtimePermissionsRevoked = false;
12059        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12060
12061        boolean changedInstallPermission = false;
12062
12063        if (replace) {
12064            ps.installPermissionsFixed = false;
12065            if (!ps.isSharedUser()) {
12066                origPermissions = new PermissionsState(permissionsState);
12067                permissionsState.reset();
12068            } else {
12069                // We need to know only about runtime permission changes since the
12070                // calling code always writes the install permissions state but
12071                // the runtime ones are written only if changed. The only cases of
12072                // changed runtime permissions here are promotion of an install to
12073                // runtime and revocation of a runtime from a shared user.
12074                changedRuntimePermissionUserIds =
12075                        mPermissionManager.revokeUnusedSharedUserPermissions(
12076                                ps.sharedUser, UserManagerService.getInstance().getUserIds());
12077                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12078                    runtimePermissionsRevoked = true;
12079                }
12080            }
12081        }
12082
12083        permissionsState.setGlobalGids(mGlobalGids);
12084
12085        final int N = pkg.requestedPermissions.size();
12086        for (int i=0; i<N; i++) {
12087            final String name = pkg.requestedPermissions.get(i);
12088            final BasePermission bp = (BasePermission) mPermissionManager.getPermissionTEMP(name);
12089            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12090                    >= Build.VERSION_CODES.M;
12091
12092            if (DEBUG_INSTALL) {
12093                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12094            }
12095
12096            if (bp == null || bp.getSourcePackageSetting() == null) {
12097                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12098                    if (DEBUG_PERMISSIONS) {
12099                        Slog.i(TAG, "Unknown permission " + name
12100                                + " in package " + pkg.packageName);
12101                    }
12102                }
12103                continue;
12104            }
12105
12106
12107            // Limit ephemeral apps to ephemeral allowed permissions.
12108            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12109                if (DEBUG_PERMISSIONS) {
12110                    Log.i(TAG, "Denying non-ephemeral permission " + bp.getName() + " for package "
12111                            + pkg.packageName);
12112                }
12113                continue;
12114            }
12115
12116            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12117                if (DEBUG_PERMISSIONS) {
12118                    Log.i(TAG, "Denying runtime-only permission " + bp.getName() + " for package "
12119                            + pkg.packageName);
12120                }
12121                continue;
12122            }
12123
12124            final String perm = bp.getName();
12125            boolean allowedSig = false;
12126            int grant = GRANT_DENIED;
12127
12128            // Keep track of app op permissions.
12129            if (bp.isAppOp()) {
12130                mSettings.addAppOpPackage(perm, pkg.packageName);
12131            }
12132
12133            if (bp.isNormal()) {
12134                // For all apps normal permissions are install time ones.
12135                grant = GRANT_INSTALL;
12136            } else if (bp.isRuntime()) {
12137                // If a permission review is required for legacy apps we represent
12138                // their permissions as always granted runtime ones since we need
12139                // to keep the review required permission flag per user while an
12140                // install permission's state is shared across all users.
12141                if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12142                    // For legacy apps dangerous permissions are install time ones.
12143                    grant = GRANT_INSTALL;
12144                } else if (origPermissions.hasInstallPermission(bp.getName())) {
12145                    // For legacy apps that became modern, install becomes runtime.
12146                    grant = GRANT_UPGRADE;
12147                } else if (mPromoteSystemApps
12148                        && isSystemApp(ps)
12149                        && mExistingSystemPackages.contains(ps.name)) {
12150                    // For legacy system apps, install becomes runtime.
12151                    // We cannot check hasInstallPermission() for system apps since those
12152                    // permissions were granted implicitly and not persisted pre-M.
12153                    grant = GRANT_UPGRADE;
12154                } else {
12155                    // For modern apps keep runtime permissions unchanged.
12156                    grant = GRANT_RUNTIME;
12157                }
12158            } else if (bp.isSignature()) {
12159                // For all apps signature permissions are install time ones.
12160                allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12161                if (allowedSig) {
12162                    grant = GRANT_INSTALL;
12163                }
12164            }
12165
12166            if (DEBUG_PERMISSIONS) {
12167                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12168            }
12169
12170            if (grant != GRANT_DENIED) {
12171                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12172                    // If this is an existing, non-system package, then
12173                    // we can't add any new permissions to it.
12174                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12175                        // Except...  if this is a permission that was added
12176                        // to the platform (note: need to only do this when
12177                        // updating the platform).
12178                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12179                            grant = GRANT_DENIED;
12180                        }
12181                    }
12182                }
12183
12184                switch (grant) {
12185                    case GRANT_INSTALL: {
12186                        // Revoke this as runtime permission to handle the case of
12187                        // a runtime permission being downgraded to an install one.
12188                        // Also in permission review mode we keep dangerous permissions
12189                        // for legacy apps
12190                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12191                            if (origPermissions.getRuntimePermissionState(
12192                                    perm, userId) != null) {
12193                                // Revoke the runtime permission and clear the flags.
12194                                origPermissions.revokeRuntimePermission(bp, userId);
12195                                origPermissions.updatePermissionFlags(bp, userId,
12196                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12197                                // If we revoked a permission permission, we have to write.
12198                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12199                                        changedRuntimePermissionUserIds, userId);
12200                            }
12201                        }
12202                        // Grant an install permission.
12203                        if (permissionsState.grantInstallPermission(bp) !=
12204                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12205                            changedInstallPermission = true;
12206                        }
12207                    } break;
12208
12209                    case GRANT_RUNTIME: {
12210                        // Grant previously granted runtime permissions.
12211                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12212                            PermissionState permissionState = origPermissions
12213                                    .getRuntimePermissionState(perm, userId);
12214                            int flags = permissionState != null
12215                                    ? permissionState.getFlags() : 0;
12216                            if (origPermissions.hasRuntimePermission(perm, userId)) {
12217                                // Don't propagate the permission in a permission review mode if
12218                                // the former was revoked, i.e. marked to not propagate on upgrade.
12219                                // Note that in a permission review mode install permissions are
12220                                // represented as constantly granted runtime ones since we need to
12221                                // keep a per user state associated with the permission. Also the
12222                                // revoke on upgrade flag is no longer applicable and is reset.
12223                                final boolean revokeOnUpgrade = (flags & PackageManager
12224                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12225                                if (revokeOnUpgrade) {
12226                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12227                                    // Since we changed the flags, we have to write.
12228                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12229                                            changedRuntimePermissionUserIds, userId);
12230                                }
12231                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12232                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12233                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12234                                        // If we cannot put the permission as it was,
12235                                        // we have to write.
12236                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12237                                                changedRuntimePermissionUserIds, userId);
12238                                    }
12239                                }
12240
12241                                // If the app supports runtime permissions no need for a review.
12242                                if (mPermissionReviewRequired
12243                                        && appSupportsRuntimePermissions
12244                                        && (flags & PackageManager
12245                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12246                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12247                                    // Since we changed the flags, we have to write.
12248                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12249                                            changedRuntimePermissionUserIds, userId);
12250                                }
12251                            } else if (mPermissionReviewRequired
12252                                    && !appSupportsRuntimePermissions) {
12253                                // For legacy apps that need a permission review, every new
12254                                // runtime permission is granted but it is pending a review.
12255                                // We also need to review only platform defined runtime
12256                                // permissions as these are the only ones the platform knows
12257                                // how to disable the API to simulate revocation as legacy
12258                                // apps don't expect to run with revoked permissions.
12259                                if (PLATFORM_PACKAGE_NAME.equals(bp.getSourcePackageName())) {
12260                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12261                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12262                                        // We changed the flags, hence have to write.
12263                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12264                                                changedRuntimePermissionUserIds, userId);
12265                                    }
12266                                }
12267                                if (permissionsState.grantRuntimePermission(bp, userId)
12268                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12269                                    // We changed the permission, hence have to write.
12270                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12271                                            changedRuntimePermissionUserIds, userId);
12272                                }
12273                            }
12274                            // Propagate the permission flags.
12275                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12276                        }
12277                    } break;
12278
12279                    case GRANT_UPGRADE: {
12280                        // Grant runtime permissions for a previously held install permission.
12281                        PermissionState permissionState = origPermissions
12282                                .getInstallPermissionState(perm);
12283                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12284
12285                        if (origPermissions.revokeInstallPermission(bp)
12286                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12287                            // We will be transferring the permission flags, so clear them.
12288                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12289                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12290                            changedInstallPermission = true;
12291                        }
12292
12293                        // If the permission is not to be promoted to runtime we ignore it and
12294                        // also its other flags as they are not applicable to install permissions.
12295                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12296                            for (int userId : currentUserIds) {
12297                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12298                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12299                                    // Transfer the permission flags.
12300                                    permissionsState.updatePermissionFlags(bp, userId,
12301                                            flags, flags);
12302                                    // If we granted the permission, we have to write.
12303                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12304                                            changedRuntimePermissionUserIds, userId);
12305                                }
12306                            }
12307                        }
12308                    } break;
12309
12310                    default: {
12311                        if (packageOfInterest == null
12312                                || packageOfInterest.equals(pkg.packageName)) {
12313                            if (DEBUG_PERMISSIONS) {
12314                                Slog.i(TAG, "Not granting permission " + perm
12315                                        + " to package " + pkg.packageName
12316                                        + " because it was previously installed without");
12317                            }
12318                        }
12319                    } break;
12320                }
12321            } else {
12322                if (permissionsState.revokeInstallPermission(bp) !=
12323                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12324                    // Also drop the permission flags.
12325                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12326                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12327                    changedInstallPermission = true;
12328                    Slog.i(TAG, "Un-granting permission " + perm
12329                            + " from package " + pkg.packageName
12330                            + " (protectionLevel=" + bp.getProtectionLevel()
12331                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12332                            + ")");
12333                } else if (bp.isAppOp()) {
12334                    // Don't print warning for app op permissions, since it is fine for them
12335                    // not to be granted, there is a UI for the user to decide.
12336                    if (DEBUG_PERMISSIONS
12337                            && (packageOfInterest == null
12338                                    || packageOfInterest.equals(pkg.packageName))) {
12339                        Slog.i(TAG, "Not granting permission " + perm
12340                                + " to package " + pkg.packageName
12341                                + " (protectionLevel=" + bp.getProtectionLevel()
12342                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12343                                + ")");
12344                    }
12345                }
12346            }
12347        }
12348
12349        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12350                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12351            // This is the first that we have heard about this package, so the
12352            // permissions we have now selected are fixed until explicitly
12353            // changed.
12354            ps.installPermissionsFixed = true;
12355        }
12356
12357        // Persist the runtime permissions state for users with changes. If permissions
12358        // were revoked because no app in the shared user declares them we have to
12359        // write synchronously to avoid losing runtime permissions state.
12360        for (int userId : changedRuntimePermissionUserIds) {
12361            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12362        }
12363    }
12364
12365    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12366        boolean allowed = false;
12367        final int NP = PackageParser.NEW_PERMISSIONS.length;
12368        for (int ip=0; ip<NP; ip++) {
12369            final PackageParser.NewPermissionInfo npi
12370                    = PackageParser.NEW_PERMISSIONS[ip];
12371            if (npi.name.equals(perm)
12372                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12373                allowed = true;
12374                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12375                        + pkg.packageName);
12376                break;
12377            }
12378        }
12379        return allowed;
12380    }
12381
12382    /**
12383     * Determines whether a package is whitelisted for a particular privapp permission.
12384     *
12385     * <p>Does NOT check whether the package is a privapp, just whether it's whitelisted.
12386     *
12387     * <p>This handles parent/child apps.
12388     */
12389    private boolean hasPrivappWhitelistEntry(String perm, PackageParser.Package pkg) {
12390        ArraySet<String> wlPermissions = SystemConfig.getInstance()
12391                .getPrivAppPermissions(pkg.packageName);
12392        // Let's check if this package is whitelisted...
12393        boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12394        // If it's not, we'll also tail-recurse to the parent.
12395        return whitelisted ||
12396                pkg.parentPackage != null && hasPrivappWhitelistEntry(perm, pkg.parentPackage);
12397    }
12398
12399    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12400            BasePermission bp, PermissionsState origPermissions) {
12401        boolean oemPermission = bp.isOEM();
12402        boolean privilegedPermission = bp.isPrivileged();
12403        boolean privappPermissionsDisable =
12404                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12405        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.getSourcePackageName());
12406        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12407        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12408                && !platformPackage && platformPermission) {
12409            if (!hasPrivappWhitelistEntry(perm, pkg)) {
12410                Slog.w(TAG, "Privileged permission " + perm + " for package "
12411                        + pkg.packageName + " - not in privapp-permissions whitelist");
12412                // Only report violations for apps on system image
12413                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12414                    // it's only a reportable violation if the permission isn't explicitly denied
12415                    final ArraySet<String> deniedPermissions = SystemConfig.getInstance()
12416                            .getPrivAppDenyPermissions(pkg.packageName);
12417                    final boolean permissionViolation =
12418                            deniedPermissions == null || !deniedPermissions.contains(perm);
12419                    if (permissionViolation) {
12420                        if (mPrivappPermissionsViolations == null) {
12421                            mPrivappPermissionsViolations = new ArraySet<>();
12422                        }
12423                        mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12424                    } else {
12425                        return false;
12426                    }
12427                }
12428                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12429                    return false;
12430                }
12431            }
12432        }
12433        boolean allowed = (compareSignatures(
12434                bp.getSourcePackageSetting().signatures.mSignatures, pkg.mSignatures)
12435                        == PackageManager.SIGNATURE_MATCH)
12436                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12437                        == PackageManager.SIGNATURE_MATCH);
12438        if (!allowed && (privilegedPermission || oemPermission)) {
12439            if (isSystemApp(pkg)) {
12440                // For updated system applications, a privileged/oem permission
12441                // is granted only if it had been defined by the original application.
12442                if (pkg.isUpdatedSystemApp()) {
12443                    final PackageSetting sysPs = mSettings
12444                            .getDisabledSystemPkgLPr(pkg.packageName);
12445                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12446                        // If the original was granted this permission, we take
12447                        // that grant decision as read and propagate it to the
12448                        // update.
12449                        if ((privilegedPermission && sysPs.isPrivileged())
12450                                || (oemPermission && sysPs.isOem()
12451                                        && canGrantOemPermission(sysPs, perm))) {
12452                            allowed = true;
12453                        }
12454                    } else {
12455                        // The system apk may have been updated with an older
12456                        // version of the one on the data partition, but which
12457                        // granted a new system permission that it didn't have
12458                        // before.  In this case we do want to allow the app to
12459                        // now get the new permission if the ancestral apk is
12460                        // privileged to get it.
12461                        if (sysPs != null && sysPs.pkg != null
12462                                && isPackageRequestingPermission(sysPs.pkg, perm)
12463                                && ((privilegedPermission && sysPs.isPrivileged())
12464                                        || (oemPermission && sysPs.isOem()
12465                                                && canGrantOemPermission(sysPs, perm)))) {
12466                            allowed = true;
12467                        }
12468                        // Also if a privileged parent package on the system image or any of
12469                        // its children requested a privileged/oem permission, the updated child
12470                        // packages can also get the permission.
12471                        if (pkg.parentPackage != null) {
12472                            final PackageSetting disabledSysParentPs = mSettings
12473                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12474                            final PackageParser.Package disabledSysParentPkg =
12475                                    (disabledSysParentPs == null || disabledSysParentPs.pkg == null)
12476                                    ? null : disabledSysParentPs.pkg;
12477                            if (disabledSysParentPkg != null
12478                                    && ((privilegedPermission && disabledSysParentPs.isPrivileged())
12479                                            || (oemPermission && disabledSysParentPs.isOem()))) {
12480                                if (isPackageRequestingPermission(disabledSysParentPkg, perm)
12481                                        && canGrantOemPermission(disabledSysParentPs, perm)) {
12482                                    allowed = true;
12483                                } else if (disabledSysParentPkg.childPackages != null) {
12484                                    final int count = disabledSysParentPkg.childPackages.size();
12485                                    for (int i = 0; i < count; i++) {
12486                                        final PackageParser.Package disabledSysChildPkg =
12487                                                disabledSysParentPkg.childPackages.get(i);
12488                                        final PackageSetting disabledSysChildPs =
12489                                                mSettings.getDisabledSystemPkgLPr(
12490                                                        disabledSysChildPkg.packageName);
12491                                        if (isPackageRequestingPermission(disabledSysChildPkg, perm)
12492                                                && canGrantOemPermission(
12493                                                        disabledSysChildPs, perm)) {
12494                                            allowed = true;
12495                                            break;
12496                                        }
12497                                    }
12498                                }
12499                            }
12500                        }
12501                    }
12502                } else {
12503                    allowed = (privilegedPermission && isPrivilegedApp(pkg))
12504                            || (oemPermission && isOemApp(pkg)
12505                                    && canGrantOemPermission(
12506                                            mSettings.getPackageLPr(pkg.packageName), perm));
12507                }
12508            }
12509        }
12510        if (!allowed) {
12511            if (!allowed
12512                    && bp.isPre23()
12513                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12514                // If this was a previously normal/dangerous permission that got moved
12515                // to a system permission as part of the runtime permission redesign, then
12516                // we still want to blindly grant it to old apps.
12517                allowed = true;
12518            }
12519            if (!allowed && bp.isInstaller()
12520                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12521                // If this permission is to be granted to the system installer and
12522                // this app is an installer, then it gets the permission.
12523                allowed = true;
12524            }
12525            if (!allowed && bp.isVerifier()
12526                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12527                // If this permission is to be granted to the system verifier and
12528                // this app is a verifier, then it gets the permission.
12529                allowed = true;
12530            }
12531            if (!allowed && bp.isPreInstalled()
12532                    && isSystemApp(pkg)) {
12533                // Any pre-installed system app is allowed to get this permission.
12534                allowed = true;
12535            }
12536            if (!allowed && bp.isDevelopment()) {
12537                // For development permissions, a development permission
12538                // is granted only if it was already granted.
12539                allowed = origPermissions.hasInstallPermission(perm);
12540            }
12541            if (!allowed && bp.isSetup()
12542                    && pkg.packageName.equals(mSetupWizardPackage)) {
12543                // If this permission is to be granted to the system setup wizard and
12544                // this app is a setup wizard, then it gets the permission.
12545                allowed = true;
12546            }
12547        }
12548        return allowed;
12549    }
12550
12551    private static boolean canGrantOemPermission(PackageSetting ps, String permission) {
12552        if (!ps.isOem()) {
12553            return false;
12554        }
12555        // all oem permissions must explicitly be granted or denied
12556        final Boolean granted =
12557                SystemConfig.getInstance().getOemPermissions(ps.name).get(permission);
12558        if (granted == null) {
12559            throw new IllegalStateException("OEM permission" + permission + " requested by package "
12560                    + ps.name + " must be explicitly declared granted or not");
12561        }
12562        return Boolean.TRUE == granted;
12563    }
12564
12565    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12566        final int permCount = pkg.requestedPermissions.size();
12567        for (int j = 0; j < permCount; j++) {
12568            String requestedPermission = pkg.requestedPermissions.get(j);
12569            if (permission.equals(requestedPermission)) {
12570                return true;
12571            }
12572        }
12573        return false;
12574    }
12575
12576    final class ActivityIntentResolver
12577            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12578        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12579                boolean defaultOnly, int userId) {
12580            if (!sUserManager.exists(userId)) return null;
12581            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12582            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12583        }
12584
12585        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12586                int userId) {
12587            if (!sUserManager.exists(userId)) return null;
12588            mFlags = flags;
12589            return super.queryIntent(intent, resolvedType,
12590                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12591                    userId);
12592        }
12593
12594        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12595                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12596            if (!sUserManager.exists(userId)) return null;
12597            if (packageActivities == null) {
12598                return null;
12599            }
12600            mFlags = flags;
12601            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12602            final int N = packageActivities.size();
12603            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12604                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12605
12606            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12607            for (int i = 0; i < N; ++i) {
12608                intentFilters = packageActivities.get(i).intents;
12609                if (intentFilters != null && intentFilters.size() > 0) {
12610                    PackageParser.ActivityIntentInfo[] array =
12611                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12612                    intentFilters.toArray(array);
12613                    listCut.add(array);
12614                }
12615            }
12616            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12617        }
12618
12619        /**
12620         * Finds a privileged activity that matches the specified activity names.
12621         */
12622        private PackageParser.Activity findMatchingActivity(
12623                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12624            for (PackageParser.Activity sysActivity : activityList) {
12625                if (sysActivity.info.name.equals(activityInfo.name)) {
12626                    return sysActivity;
12627                }
12628                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12629                    return sysActivity;
12630                }
12631                if (sysActivity.info.targetActivity != null) {
12632                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12633                        return sysActivity;
12634                    }
12635                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12636                        return sysActivity;
12637                    }
12638                }
12639            }
12640            return null;
12641        }
12642
12643        public class IterGenerator<E> {
12644            public Iterator<E> generate(ActivityIntentInfo info) {
12645                return null;
12646            }
12647        }
12648
12649        public class ActionIterGenerator extends IterGenerator<String> {
12650            @Override
12651            public Iterator<String> generate(ActivityIntentInfo info) {
12652                return info.actionsIterator();
12653            }
12654        }
12655
12656        public class CategoriesIterGenerator extends IterGenerator<String> {
12657            @Override
12658            public Iterator<String> generate(ActivityIntentInfo info) {
12659                return info.categoriesIterator();
12660            }
12661        }
12662
12663        public class SchemesIterGenerator extends IterGenerator<String> {
12664            @Override
12665            public Iterator<String> generate(ActivityIntentInfo info) {
12666                return info.schemesIterator();
12667            }
12668        }
12669
12670        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12671            @Override
12672            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12673                return info.authoritiesIterator();
12674            }
12675        }
12676
12677        /**
12678         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12679         * MODIFIED. Do not pass in a list that should not be changed.
12680         */
12681        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12682                IterGenerator<T> generator, Iterator<T> searchIterator) {
12683            // loop through the set of actions; every one must be found in the intent filter
12684            while (searchIterator.hasNext()) {
12685                // we must have at least one filter in the list to consider a match
12686                if (intentList.size() == 0) {
12687                    break;
12688                }
12689
12690                final T searchAction = searchIterator.next();
12691
12692                // loop through the set of intent filters
12693                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12694                while (intentIter.hasNext()) {
12695                    final ActivityIntentInfo intentInfo = intentIter.next();
12696                    boolean selectionFound = false;
12697
12698                    // loop through the intent filter's selection criteria; at least one
12699                    // of them must match the searched criteria
12700                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12701                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12702                        final T intentSelection = intentSelectionIter.next();
12703                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12704                            selectionFound = true;
12705                            break;
12706                        }
12707                    }
12708
12709                    // the selection criteria wasn't found in this filter's set; this filter
12710                    // is not a potential match
12711                    if (!selectionFound) {
12712                        intentIter.remove();
12713                    }
12714                }
12715            }
12716        }
12717
12718        private boolean isProtectedAction(ActivityIntentInfo filter) {
12719            final Iterator<String> actionsIter = filter.actionsIterator();
12720            while (actionsIter != null && actionsIter.hasNext()) {
12721                final String filterAction = actionsIter.next();
12722                if (PROTECTED_ACTIONS.contains(filterAction)) {
12723                    return true;
12724                }
12725            }
12726            return false;
12727        }
12728
12729        /**
12730         * Adjusts the priority of the given intent filter according to policy.
12731         * <p>
12732         * <ul>
12733         * <li>The priority for non privileged applications is capped to '0'</li>
12734         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12735         * <li>The priority for unbundled updates to privileged applications is capped to the
12736         *      priority defined on the system partition</li>
12737         * </ul>
12738         * <p>
12739         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12740         * allowed to obtain any priority on any action.
12741         */
12742        private void adjustPriority(
12743                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12744            // nothing to do; priority is fine as-is
12745            if (intent.getPriority() <= 0) {
12746                return;
12747            }
12748
12749            final ActivityInfo activityInfo = intent.activity.info;
12750            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12751
12752            final boolean privilegedApp =
12753                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12754            if (!privilegedApp) {
12755                // non-privileged applications can never define a priority >0
12756                if (DEBUG_FILTERS) {
12757                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12758                            + " package: " + applicationInfo.packageName
12759                            + " activity: " + intent.activity.className
12760                            + " origPrio: " + intent.getPriority());
12761                }
12762                intent.setPriority(0);
12763                return;
12764            }
12765
12766            if (systemActivities == null) {
12767                // the system package is not disabled; we're parsing the system partition
12768                if (isProtectedAction(intent)) {
12769                    if (mDeferProtectedFilters) {
12770                        // We can't deal with these just yet. No component should ever obtain a
12771                        // >0 priority for a protected actions, with ONE exception -- the setup
12772                        // wizard. The setup wizard, however, cannot be known until we're able to
12773                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12774                        // until all intent filters have been processed. Chicken, meet egg.
12775                        // Let the filter temporarily have a high priority and rectify the
12776                        // priorities after all system packages have been scanned.
12777                        mProtectedFilters.add(intent);
12778                        if (DEBUG_FILTERS) {
12779                            Slog.i(TAG, "Protected action; save for later;"
12780                                    + " package: " + applicationInfo.packageName
12781                                    + " activity: " + intent.activity.className
12782                                    + " origPrio: " + intent.getPriority());
12783                        }
12784                        return;
12785                    } else {
12786                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12787                            Slog.i(TAG, "No setup wizard;"
12788                                + " All protected intents capped to priority 0");
12789                        }
12790                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12791                            if (DEBUG_FILTERS) {
12792                                Slog.i(TAG, "Found setup wizard;"
12793                                    + " allow priority " + intent.getPriority() + ";"
12794                                    + " package: " + intent.activity.info.packageName
12795                                    + " activity: " + intent.activity.className
12796                                    + " priority: " + intent.getPriority());
12797                            }
12798                            // setup wizard gets whatever it wants
12799                            return;
12800                        }
12801                        if (DEBUG_FILTERS) {
12802                            Slog.i(TAG, "Protected action; cap priority to 0;"
12803                                    + " package: " + intent.activity.info.packageName
12804                                    + " activity: " + intent.activity.className
12805                                    + " origPrio: " + intent.getPriority());
12806                        }
12807                        intent.setPriority(0);
12808                        return;
12809                    }
12810                }
12811                // privileged apps on the system image get whatever priority they request
12812                return;
12813            }
12814
12815            // privileged app unbundled update ... try to find the same activity
12816            final PackageParser.Activity foundActivity =
12817                    findMatchingActivity(systemActivities, activityInfo);
12818            if (foundActivity == null) {
12819                // this is a new activity; it cannot obtain >0 priority
12820                if (DEBUG_FILTERS) {
12821                    Slog.i(TAG, "New activity; cap priority to 0;"
12822                            + " package: " + applicationInfo.packageName
12823                            + " activity: " + intent.activity.className
12824                            + " origPrio: " + intent.getPriority());
12825                }
12826                intent.setPriority(0);
12827                return;
12828            }
12829
12830            // found activity, now check for filter equivalence
12831
12832            // a shallow copy is enough; we modify the list, not its contents
12833            final List<ActivityIntentInfo> intentListCopy =
12834                    new ArrayList<>(foundActivity.intents);
12835            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12836
12837            // find matching action subsets
12838            final Iterator<String> actionsIterator = intent.actionsIterator();
12839            if (actionsIterator != null) {
12840                getIntentListSubset(
12841                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12842                if (intentListCopy.size() == 0) {
12843                    // no more intents to match; we're not equivalent
12844                    if (DEBUG_FILTERS) {
12845                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12846                                + " package: " + applicationInfo.packageName
12847                                + " activity: " + intent.activity.className
12848                                + " origPrio: " + intent.getPriority());
12849                    }
12850                    intent.setPriority(0);
12851                    return;
12852                }
12853            }
12854
12855            // find matching category subsets
12856            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12857            if (categoriesIterator != null) {
12858                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12859                        categoriesIterator);
12860                if (intentListCopy.size() == 0) {
12861                    // no more intents to match; we're not equivalent
12862                    if (DEBUG_FILTERS) {
12863                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12864                                + " package: " + applicationInfo.packageName
12865                                + " activity: " + intent.activity.className
12866                                + " origPrio: " + intent.getPriority());
12867                    }
12868                    intent.setPriority(0);
12869                    return;
12870                }
12871            }
12872
12873            // find matching schemes subsets
12874            final Iterator<String> schemesIterator = intent.schemesIterator();
12875            if (schemesIterator != null) {
12876                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12877                        schemesIterator);
12878                if (intentListCopy.size() == 0) {
12879                    // no more intents to match; we're not equivalent
12880                    if (DEBUG_FILTERS) {
12881                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12882                                + " package: " + applicationInfo.packageName
12883                                + " activity: " + intent.activity.className
12884                                + " origPrio: " + intent.getPriority());
12885                    }
12886                    intent.setPriority(0);
12887                    return;
12888                }
12889            }
12890
12891            // find matching authorities subsets
12892            final Iterator<IntentFilter.AuthorityEntry>
12893                    authoritiesIterator = intent.authoritiesIterator();
12894            if (authoritiesIterator != null) {
12895                getIntentListSubset(intentListCopy,
12896                        new AuthoritiesIterGenerator(),
12897                        authoritiesIterator);
12898                if (intentListCopy.size() == 0) {
12899                    // no more intents to match; we're not equivalent
12900                    if (DEBUG_FILTERS) {
12901                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12902                                + " package: " + applicationInfo.packageName
12903                                + " activity: " + intent.activity.className
12904                                + " origPrio: " + intent.getPriority());
12905                    }
12906                    intent.setPriority(0);
12907                    return;
12908                }
12909            }
12910
12911            // we found matching filter(s); app gets the max priority of all intents
12912            int cappedPriority = 0;
12913            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12914                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12915            }
12916            if (intent.getPriority() > cappedPriority) {
12917                if (DEBUG_FILTERS) {
12918                    Slog.i(TAG, "Found matching filter(s);"
12919                            + " cap priority to " + cappedPriority + ";"
12920                            + " package: " + applicationInfo.packageName
12921                            + " activity: " + intent.activity.className
12922                            + " origPrio: " + intent.getPriority());
12923                }
12924                intent.setPriority(cappedPriority);
12925                return;
12926            }
12927            // all this for nothing; the requested priority was <= what was on the system
12928        }
12929
12930        public final void addActivity(PackageParser.Activity a, String type) {
12931            mActivities.put(a.getComponentName(), a);
12932            if (DEBUG_SHOW_INFO)
12933                Log.v(
12934                TAG, "  " + type + " " +
12935                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12936            if (DEBUG_SHOW_INFO)
12937                Log.v(TAG, "    Class=" + a.info.name);
12938            final int NI = a.intents.size();
12939            for (int j=0; j<NI; j++) {
12940                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12941                if ("activity".equals(type)) {
12942                    final PackageSetting ps =
12943                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12944                    final List<PackageParser.Activity> systemActivities =
12945                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12946                    adjustPriority(systemActivities, intent);
12947                }
12948                if (DEBUG_SHOW_INFO) {
12949                    Log.v(TAG, "    IntentFilter:");
12950                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12951                }
12952                if (!intent.debugCheck()) {
12953                    Log.w(TAG, "==> For Activity " + a.info.name);
12954                }
12955                addFilter(intent);
12956            }
12957        }
12958
12959        public final void removeActivity(PackageParser.Activity a, String type) {
12960            mActivities.remove(a.getComponentName());
12961            if (DEBUG_SHOW_INFO) {
12962                Log.v(TAG, "  " + type + " "
12963                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12964                                : a.info.name) + ":");
12965                Log.v(TAG, "    Class=" + a.info.name);
12966            }
12967            final int NI = a.intents.size();
12968            for (int j=0; j<NI; j++) {
12969                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12970                if (DEBUG_SHOW_INFO) {
12971                    Log.v(TAG, "    IntentFilter:");
12972                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12973                }
12974                removeFilter(intent);
12975            }
12976        }
12977
12978        @Override
12979        protected boolean allowFilterResult(
12980                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12981            ActivityInfo filterAi = filter.activity.info;
12982            for (int i=dest.size()-1; i>=0; i--) {
12983                ActivityInfo destAi = dest.get(i).activityInfo;
12984                if (destAi.name == filterAi.name
12985                        && destAi.packageName == filterAi.packageName) {
12986                    return false;
12987                }
12988            }
12989            return true;
12990        }
12991
12992        @Override
12993        protected ActivityIntentInfo[] newArray(int size) {
12994            return new ActivityIntentInfo[size];
12995        }
12996
12997        @Override
12998        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12999            if (!sUserManager.exists(userId)) return true;
13000            PackageParser.Package p = filter.activity.owner;
13001            if (p != null) {
13002                PackageSetting ps = (PackageSetting)p.mExtras;
13003                if (ps != null) {
13004                    // System apps are never considered stopped for purposes of
13005                    // filtering, because there may be no way for the user to
13006                    // actually re-launch them.
13007                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13008                            && ps.getStopped(userId);
13009                }
13010            }
13011            return false;
13012        }
13013
13014        @Override
13015        protected boolean isPackageForFilter(String packageName,
13016                PackageParser.ActivityIntentInfo info) {
13017            return packageName.equals(info.activity.owner.packageName);
13018        }
13019
13020        @Override
13021        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13022                int match, int userId) {
13023            if (!sUserManager.exists(userId)) return null;
13024            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13025                return null;
13026            }
13027            final PackageParser.Activity activity = info.activity;
13028            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13029            if (ps == null) {
13030                return null;
13031            }
13032            final PackageUserState userState = ps.readUserState(userId);
13033            ActivityInfo ai =
13034                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13035            if (ai == null) {
13036                return null;
13037            }
13038            final boolean matchExplicitlyVisibleOnly =
13039                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13040            final boolean matchVisibleToInstantApp =
13041                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13042            final boolean componentVisible =
13043                    matchVisibleToInstantApp
13044                    && info.isVisibleToInstantApp()
13045                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13046            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13047            // throw out filters that aren't visible to ephemeral apps
13048            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13049                return null;
13050            }
13051            // throw out instant app filters if we're not explicitly requesting them
13052            if (!matchInstantApp && userState.instantApp) {
13053                return null;
13054            }
13055            // throw out instant app filters if updates are available; will trigger
13056            // instant app resolution
13057            if (userState.instantApp && ps.isUpdateAvailable()) {
13058                return null;
13059            }
13060            final ResolveInfo res = new ResolveInfo();
13061            res.activityInfo = ai;
13062            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13063                res.filter = info;
13064            }
13065            if (info != null) {
13066                res.handleAllWebDataURI = info.handleAllWebDataURI();
13067            }
13068            res.priority = info.getPriority();
13069            res.preferredOrder = activity.owner.mPreferredOrder;
13070            //System.out.println("Result: " + res.activityInfo.className +
13071            //                   " = " + res.priority);
13072            res.match = match;
13073            res.isDefault = info.hasDefault;
13074            res.labelRes = info.labelRes;
13075            res.nonLocalizedLabel = info.nonLocalizedLabel;
13076            if (userNeedsBadging(userId)) {
13077                res.noResourceId = true;
13078            } else {
13079                res.icon = info.icon;
13080            }
13081            res.iconResourceId = info.icon;
13082            res.system = res.activityInfo.applicationInfo.isSystemApp();
13083            res.isInstantAppAvailable = userState.instantApp;
13084            return res;
13085        }
13086
13087        @Override
13088        protected void sortResults(List<ResolveInfo> results) {
13089            Collections.sort(results, mResolvePrioritySorter);
13090        }
13091
13092        @Override
13093        protected void dumpFilter(PrintWriter out, String prefix,
13094                PackageParser.ActivityIntentInfo filter) {
13095            out.print(prefix); out.print(
13096                    Integer.toHexString(System.identityHashCode(filter.activity)));
13097                    out.print(' ');
13098                    filter.activity.printComponentShortName(out);
13099                    out.print(" filter ");
13100                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13101        }
13102
13103        @Override
13104        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13105            return filter.activity;
13106        }
13107
13108        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13109            PackageParser.Activity activity = (PackageParser.Activity)label;
13110            out.print(prefix); out.print(
13111                    Integer.toHexString(System.identityHashCode(activity)));
13112                    out.print(' ');
13113                    activity.printComponentShortName(out);
13114            if (count > 1) {
13115                out.print(" ("); out.print(count); out.print(" filters)");
13116            }
13117            out.println();
13118        }
13119
13120        // Keys are String (activity class name), values are Activity.
13121        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13122                = new ArrayMap<ComponentName, PackageParser.Activity>();
13123        private int mFlags;
13124    }
13125
13126    private final class ServiceIntentResolver
13127            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13128        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13129                boolean defaultOnly, int userId) {
13130            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13131            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13132        }
13133
13134        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13135                int userId) {
13136            if (!sUserManager.exists(userId)) return null;
13137            mFlags = flags;
13138            return super.queryIntent(intent, resolvedType,
13139                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13140                    userId);
13141        }
13142
13143        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13144                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13145            if (!sUserManager.exists(userId)) return null;
13146            if (packageServices == null) {
13147                return null;
13148            }
13149            mFlags = flags;
13150            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13151            final int N = packageServices.size();
13152            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13153                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13154
13155            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13156            for (int i = 0; i < N; ++i) {
13157                intentFilters = packageServices.get(i).intents;
13158                if (intentFilters != null && intentFilters.size() > 0) {
13159                    PackageParser.ServiceIntentInfo[] array =
13160                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13161                    intentFilters.toArray(array);
13162                    listCut.add(array);
13163                }
13164            }
13165            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13166        }
13167
13168        public final void addService(PackageParser.Service s) {
13169            mServices.put(s.getComponentName(), s);
13170            if (DEBUG_SHOW_INFO) {
13171                Log.v(TAG, "  "
13172                        + (s.info.nonLocalizedLabel != null
13173                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13174                Log.v(TAG, "    Class=" + s.info.name);
13175            }
13176            final int NI = s.intents.size();
13177            int j;
13178            for (j=0; j<NI; j++) {
13179                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13180                if (DEBUG_SHOW_INFO) {
13181                    Log.v(TAG, "    IntentFilter:");
13182                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13183                }
13184                if (!intent.debugCheck()) {
13185                    Log.w(TAG, "==> For Service " + s.info.name);
13186                }
13187                addFilter(intent);
13188            }
13189        }
13190
13191        public final void removeService(PackageParser.Service s) {
13192            mServices.remove(s.getComponentName());
13193            if (DEBUG_SHOW_INFO) {
13194                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13195                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13196                Log.v(TAG, "    Class=" + s.info.name);
13197            }
13198            final int NI = s.intents.size();
13199            int j;
13200            for (j=0; j<NI; j++) {
13201                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13202                if (DEBUG_SHOW_INFO) {
13203                    Log.v(TAG, "    IntentFilter:");
13204                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13205                }
13206                removeFilter(intent);
13207            }
13208        }
13209
13210        @Override
13211        protected boolean allowFilterResult(
13212                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13213            ServiceInfo filterSi = filter.service.info;
13214            for (int i=dest.size()-1; i>=0; i--) {
13215                ServiceInfo destAi = dest.get(i).serviceInfo;
13216                if (destAi.name == filterSi.name
13217                        && destAi.packageName == filterSi.packageName) {
13218                    return false;
13219                }
13220            }
13221            return true;
13222        }
13223
13224        @Override
13225        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13226            return new PackageParser.ServiceIntentInfo[size];
13227        }
13228
13229        @Override
13230        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13231            if (!sUserManager.exists(userId)) return true;
13232            PackageParser.Package p = filter.service.owner;
13233            if (p != null) {
13234                PackageSetting ps = (PackageSetting)p.mExtras;
13235                if (ps != null) {
13236                    // System apps are never considered stopped for purposes of
13237                    // filtering, because there may be no way for the user to
13238                    // actually re-launch them.
13239                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13240                            && ps.getStopped(userId);
13241                }
13242            }
13243            return false;
13244        }
13245
13246        @Override
13247        protected boolean isPackageForFilter(String packageName,
13248                PackageParser.ServiceIntentInfo info) {
13249            return packageName.equals(info.service.owner.packageName);
13250        }
13251
13252        @Override
13253        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13254                int match, int userId) {
13255            if (!sUserManager.exists(userId)) return null;
13256            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13257            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13258                return null;
13259            }
13260            final PackageParser.Service service = info.service;
13261            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13262            if (ps == null) {
13263                return null;
13264            }
13265            final PackageUserState userState = ps.readUserState(userId);
13266            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13267                    userState, userId);
13268            if (si == null) {
13269                return null;
13270            }
13271            final boolean matchVisibleToInstantApp =
13272                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13273            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13274            // throw out filters that aren't visible to ephemeral apps
13275            if (matchVisibleToInstantApp
13276                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13277                return null;
13278            }
13279            // throw out ephemeral filters if we're not explicitly requesting them
13280            if (!isInstantApp && userState.instantApp) {
13281                return null;
13282            }
13283            // throw out instant app filters if updates are available; will trigger
13284            // instant app resolution
13285            if (userState.instantApp && ps.isUpdateAvailable()) {
13286                return null;
13287            }
13288            final ResolveInfo res = new ResolveInfo();
13289            res.serviceInfo = si;
13290            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13291                res.filter = filter;
13292            }
13293            res.priority = info.getPriority();
13294            res.preferredOrder = service.owner.mPreferredOrder;
13295            res.match = match;
13296            res.isDefault = info.hasDefault;
13297            res.labelRes = info.labelRes;
13298            res.nonLocalizedLabel = info.nonLocalizedLabel;
13299            res.icon = info.icon;
13300            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13301            return res;
13302        }
13303
13304        @Override
13305        protected void sortResults(List<ResolveInfo> results) {
13306            Collections.sort(results, mResolvePrioritySorter);
13307        }
13308
13309        @Override
13310        protected void dumpFilter(PrintWriter out, String prefix,
13311                PackageParser.ServiceIntentInfo filter) {
13312            out.print(prefix); out.print(
13313                    Integer.toHexString(System.identityHashCode(filter.service)));
13314                    out.print(' ');
13315                    filter.service.printComponentShortName(out);
13316                    out.print(" filter ");
13317                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13318        }
13319
13320        @Override
13321        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13322            return filter.service;
13323        }
13324
13325        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13326            PackageParser.Service service = (PackageParser.Service)label;
13327            out.print(prefix); out.print(
13328                    Integer.toHexString(System.identityHashCode(service)));
13329                    out.print(' ');
13330                    service.printComponentShortName(out);
13331            if (count > 1) {
13332                out.print(" ("); out.print(count); out.print(" filters)");
13333            }
13334            out.println();
13335        }
13336
13337//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13338//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13339//            final List<ResolveInfo> retList = Lists.newArrayList();
13340//            while (i.hasNext()) {
13341//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13342//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13343//                    retList.add(resolveInfo);
13344//                }
13345//            }
13346//            return retList;
13347//        }
13348
13349        // Keys are String (activity class name), values are Activity.
13350        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13351                = new ArrayMap<ComponentName, PackageParser.Service>();
13352        private int mFlags;
13353    }
13354
13355    private final class ProviderIntentResolver
13356            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13357        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13358                boolean defaultOnly, int userId) {
13359            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13360            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13361        }
13362
13363        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13364                int userId) {
13365            if (!sUserManager.exists(userId))
13366                return null;
13367            mFlags = flags;
13368            return super.queryIntent(intent, resolvedType,
13369                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13370                    userId);
13371        }
13372
13373        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13374                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13375            if (!sUserManager.exists(userId))
13376                return null;
13377            if (packageProviders == null) {
13378                return null;
13379            }
13380            mFlags = flags;
13381            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13382            final int N = packageProviders.size();
13383            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13384                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13385
13386            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13387            for (int i = 0; i < N; ++i) {
13388                intentFilters = packageProviders.get(i).intents;
13389                if (intentFilters != null && intentFilters.size() > 0) {
13390                    PackageParser.ProviderIntentInfo[] array =
13391                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13392                    intentFilters.toArray(array);
13393                    listCut.add(array);
13394                }
13395            }
13396            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13397        }
13398
13399        public final void addProvider(PackageParser.Provider p) {
13400            if (mProviders.containsKey(p.getComponentName())) {
13401                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13402                return;
13403            }
13404
13405            mProviders.put(p.getComponentName(), p);
13406            if (DEBUG_SHOW_INFO) {
13407                Log.v(TAG, "  "
13408                        + (p.info.nonLocalizedLabel != null
13409                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13410                Log.v(TAG, "    Class=" + p.info.name);
13411            }
13412            final int NI = p.intents.size();
13413            int j;
13414            for (j = 0; j < NI; j++) {
13415                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13416                if (DEBUG_SHOW_INFO) {
13417                    Log.v(TAG, "    IntentFilter:");
13418                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13419                }
13420                if (!intent.debugCheck()) {
13421                    Log.w(TAG, "==> For Provider " + p.info.name);
13422                }
13423                addFilter(intent);
13424            }
13425        }
13426
13427        public final void removeProvider(PackageParser.Provider p) {
13428            mProviders.remove(p.getComponentName());
13429            if (DEBUG_SHOW_INFO) {
13430                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13431                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13432                Log.v(TAG, "    Class=" + p.info.name);
13433            }
13434            final int NI = p.intents.size();
13435            int j;
13436            for (j = 0; j < NI; j++) {
13437                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13438                if (DEBUG_SHOW_INFO) {
13439                    Log.v(TAG, "    IntentFilter:");
13440                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13441                }
13442                removeFilter(intent);
13443            }
13444        }
13445
13446        @Override
13447        protected boolean allowFilterResult(
13448                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13449            ProviderInfo filterPi = filter.provider.info;
13450            for (int i = dest.size() - 1; i >= 0; i--) {
13451                ProviderInfo destPi = dest.get(i).providerInfo;
13452                if (destPi.name == filterPi.name
13453                        && destPi.packageName == filterPi.packageName) {
13454                    return false;
13455                }
13456            }
13457            return true;
13458        }
13459
13460        @Override
13461        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13462            return new PackageParser.ProviderIntentInfo[size];
13463        }
13464
13465        @Override
13466        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13467            if (!sUserManager.exists(userId))
13468                return true;
13469            PackageParser.Package p = filter.provider.owner;
13470            if (p != null) {
13471                PackageSetting ps = (PackageSetting) p.mExtras;
13472                if (ps != null) {
13473                    // System apps are never considered stopped for purposes of
13474                    // filtering, because there may be no way for the user to
13475                    // actually re-launch them.
13476                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13477                            && ps.getStopped(userId);
13478                }
13479            }
13480            return false;
13481        }
13482
13483        @Override
13484        protected boolean isPackageForFilter(String packageName,
13485                PackageParser.ProviderIntentInfo info) {
13486            return packageName.equals(info.provider.owner.packageName);
13487        }
13488
13489        @Override
13490        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13491                int match, int userId) {
13492            if (!sUserManager.exists(userId))
13493                return null;
13494            final PackageParser.ProviderIntentInfo info = filter;
13495            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13496                return null;
13497            }
13498            final PackageParser.Provider provider = info.provider;
13499            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13500            if (ps == null) {
13501                return null;
13502            }
13503            final PackageUserState userState = ps.readUserState(userId);
13504            final boolean matchVisibleToInstantApp =
13505                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13506            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13507            // throw out filters that aren't visible to instant applications
13508            if (matchVisibleToInstantApp
13509                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13510                return null;
13511            }
13512            // throw out instant application filters if we're not explicitly requesting them
13513            if (!isInstantApp && userState.instantApp) {
13514                return null;
13515            }
13516            // throw out instant application filters if updates are available; will trigger
13517            // instant application resolution
13518            if (userState.instantApp && ps.isUpdateAvailable()) {
13519                return null;
13520            }
13521            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13522                    userState, userId);
13523            if (pi == null) {
13524                return null;
13525            }
13526            final ResolveInfo res = new ResolveInfo();
13527            res.providerInfo = pi;
13528            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13529                res.filter = filter;
13530            }
13531            res.priority = info.getPriority();
13532            res.preferredOrder = provider.owner.mPreferredOrder;
13533            res.match = match;
13534            res.isDefault = info.hasDefault;
13535            res.labelRes = info.labelRes;
13536            res.nonLocalizedLabel = info.nonLocalizedLabel;
13537            res.icon = info.icon;
13538            res.system = res.providerInfo.applicationInfo.isSystemApp();
13539            return res;
13540        }
13541
13542        @Override
13543        protected void sortResults(List<ResolveInfo> results) {
13544            Collections.sort(results, mResolvePrioritySorter);
13545        }
13546
13547        @Override
13548        protected void dumpFilter(PrintWriter out, String prefix,
13549                PackageParser.ProviderIntentInfo filter) {
13550            out.print(prefix);
13551            out.print(
13552                    Integer.toHexString(System.identityHashCode(filter.provider)));
13553            out.print(' ');
13554            filter.provider.printComponentShortName(out);
13555            out.print(" filter ");
13556            out.println(Integer.toHexString(System.identityHashCode(filter)));
13557        }
13558
13559        @Override
13560        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13561            return filter.provider;
13562        }
13563
13564        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13565            PackageParser.Provider provider = (PackageParser.Provider)label;
13566            out.print(prefix); out.print(
13567                    Integer.toHexString(System.identityHashCode(provider)));
13568                    out.print(' ');
13569                    provider.printComponentShortName(out);
13570            if (count > 1) {
13571                out.print(" ("); out.print(count); out.print(" filters)");
13572            }
13573            out.println();
13574        }
13575
13576        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13577                = new ArrayMap<ComponentName, PackageParser.Provider>();
13578        private int mFlags;
13579    }
13580
13581    static final class EphemeralIntentResolver
13582            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13583        /**
13584         * The result that has the highest defined order. Ordering applies on a
13585         * per-package basis. Mapping is from package name to Pair of order and
13586         * EphemeralResolveInfo.
13587         * <p>
13588         * NOTE: This is implemented as a field variable for convenience and efficiency.
13589         * By having a field variable, we're able to track filter ordering as soon as
13590         * a non-zero order is defined. Otherwise, multiple loops across the result set
13591         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13592         * this needs to be contained entirely within {@link #filterResults}.
13593         */
13594        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13595
13596        @Override
13597        protected AuxiliaryResolveInfo[] newArray(int size) {
13598            return new AuxiliaryResolveInfo[size];
13599        }
13600
13601        @Override
13602        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13603            return true;
13604        }
13605
13606        @Override
13607        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13608                int userId) {
13609            if (!sUserManager.exists(userId)) {
13610                return null;
13611            }
13612            final String packageName = responseObj.resolveInfo.getPackageName();
13613            final Integer order = responseObj.getOrder();
13614            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13615                    mOrderResult.get(packageName);
13616            // ordering is enabled and this item's order isn't high enough
13617            if (lastOrderResult != null && lastOrderResult.first >= order) {
13618                return null;
13619            }
13620            final InstantAppResolveInfo res = responseObj.resolveInfo;
13621            if (order > 0) {
13622                // non-zero order, enable ordering
13623                mOrderResult.put(packageName, new Pair<>(order, res));
13624            }
13625            return responseObj;
13626        }
13627
13628        @Override
13629        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13630            // only do work if ordering is enabled [most of the time it won't be]
13631            if (mOrderResult.size() == 0) {
13632                return;
13633            }
13634            int resultSize = results.size();
13635            for (int i = 0; i < resultSize; i++) {
13636                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13637                final String packageName = info.getPackageName();
13638                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13639                if (savedInfo == null) {
13640                    // package doesn't having ordering
13641                    continue;
13642                }
13643                if (savedInfo.second == info) {
13644                    // circled back to the highest ordered item; remove from order list
13645                    mOrderResult.remove(packageName);
13646                    if (mOrderResult.size() == 0) {
13647                        // no more ordered items
13648                        break;
13649                    }
13650                    continue;
13651                }
13652                // item has a worse order, remove it from the result list
13653                results.remove(i);
13654                resultSize--;
13655                i--;
13656            }
13657        }
13658    }
13659
13660    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13661            new Comparator<ResolveInfo>() {
13662        public int compare(ResolveInfo r1, ResolveInfo r2) {
13663            int v1 = r1.priority;
13664            int v2 = r2.priority;
13665            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13666            if (v1 != v2) {
13667                return (v1 > v2) ? -1 : 1;
13668            }
13669            v1 = r1.preferredOrder;
13670            v2 = r2.preferredOrder;
13671            if (v1 != v2) {
13672                return (v1 > v2) ? -1 : 1;
13673            }
13674            if (r1.isDefault != r2.isDefault) {
13675                return r1.isDefault ? -1 : 1;
13676            }
13677            v1 = r1.match;
13678            v2 = r2.match;
13679            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13680            if (v1 != v2) {
13681                return (v1 > v2) ? -1 : 1;
13682            }
13683            if (r1.system != r2.system) {
13684                return r1.system ? -1 : 1;
13685            }
13686            if (r1.activityInfo != null) {
13687                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13688            }
13689            if (r1.serviceInfo != null) {
13690                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13691            }
13692            if (r1.providerInfo != null) {
13693                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13694            }
13695            return 0;
13696        }
13697    };
13698
13699    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13700            new Comparator<ProviderInfo>() {
13701        public int compare(ProviderInfo p1, ProviderInfo p2) {
13702            final int v1 = p1.initOrder;
13703            final int v2 = p2.initOrder;
13704            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13705        }
13706    };
13707
13708    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13709            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13710            final int[] userIds) {
13711        mHandler.post(new Runnable() {
13712            @Override
13713            public void run() {
13714                try {
13715                    final IActivityManager am = ActivityManager.getService();
13716                    if (am == null) return;
13717                    final int[] resolvedUserIds;
13718                    if (userIds == null) {
13719                        resolvedUserIds = am.getRunningUserIds();
13720                    } else {
13721                        resolvedUserIds = userIds;
13722                    }
13723                    for (int id : resolvedUserIds) {
13724                        final Intent intent = new Intent(action,
13725                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13726                        if (extras != null) {
13727                            intent.putExtras(extras);
13728                        }
13729                        if (targetPkg != null) {
13730                            intent.setPackage(targetPkg);
13731                        }
13732                        // Modify the UID when posting to other users
13733                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13734                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
13735                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13736                            intent.putExtra(Intent.EXTRA_UID, uid);
13737                        }
13738                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13739                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13740                        if (DEBUG_BROADCASTS) {
13741                            RuntimeException here = new RuntimeException("here");
13742                            here.fillInStackTrace();
13743                            Slog.d(TAG, "Sending to user " + id + ": "
13744                                    + intent.toShortString(false, true, false, false)
13745                                    + " " + intent.getExtras(), here);
13746                        }
13747                        am.broadcastIntent(null, intent, null, finishedReceiver,
13748                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
13749                                null, finishedReceiver != null, false, id);
13750                    }
13751                } catch (RemoteException ex) {
13752                }
13753            }
13754        });
13755    }
13756
13757    /**
13758     * Check if the external storage media is available. This is true if there
13759     * is a mounted external storage medium or if the external storage is
13760     * emulated.
13761     */
13762    private boolean isExternalMediaAvailable() {
13763        return mMediaMounted || Environment.isExternalStorageEmulated();
13764    }
13765
13766    @Override
13767    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13768        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13769            return null;
13770        }
13771        // writer
13772        synchronized (mPackages) {
13773            if (!isExternalMediaAvailable()) {
13774                // If the external storage is no longer mounted at this point,
13775                // the caller may not have been able to delete all of this
13776                // packages files and can not delete any more.  Bail.
13777                return null;
13778            }
13779            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13780            if (lastPackage != null) {
13781                pkgs.remove(lastPackage);
13782            }
13783            if (pkgs.size() > 0) {
13784                return pkgs.get(0);
13785            }
13786        }
13787        return null;
13788    }
13789
13790    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13791        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13792                userId, andCode ? 1 : 0, packageName);
13793        if (mSystemReady) {
13794            msg.sendToTarget();
13795        } else {
13796            if (mPostSystemReadyMessages == null) {
13797                mPostSystemReadyMessages = new ArrayList<>();
13798            }
13799            mPostSystemReadyMessages.add(msg);
13800        }
13801    }
13802
13803    void startCleaningPackages() {
13804        // reader
13805        if (!isExternalMediaAvailable()) {
13806            return;
13807        }
13808        synchronized (mPackages) {
13809            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13810                return;
13811            }
13812        }
13813        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13814        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13815        IActivityManager am = ActivityManager.getService();
13816        if (am != null) {
13817            int dcsUid = -1;
13818            synchronized (mPackages) {
13819                if (!mDefaultContainerWhitelisted) {
13820                    mDefaultContainerWhitelisted = true;
13821                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13822                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13823                }
13824            }
13825            try {
13826                if (dcsUid > 0) {
13827                    am.backgroundWhitelistUid(dcsUid);
13828                }
13829                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13830                        UserHandle.USER_SYSTEM);
13831            } catch (RemoteException e) {
13832            }
13833        }
13834    }
13835
13836    @Override
13837    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
13838            int installFlags, String installerPackageName, int userId) {
13839        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
13840
13841        final int callingUid = Binder.getCallingUid();
13842        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13843                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
13844
13845        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13846            try {
13847                if (observer != null) {
13848                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
13849                }
13850            } catch (RemoteException re) {
13851            }
13852            return;
13853        }
13854
13855        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
13856            installFlags |= PackageManager.INSTALL_FROM_ADB;
13857
13858        } else {
13859            // Caller holds INSTALL_PACKAGES permission, so we're less strict
13860            // about installerPackageName.
13861
13862            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
13863            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
13864        }
13865
13866        UserHandle user;
13867        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
13868            user = UserHandle.ALL;
13869        } else {
13870            user = new UserHandle(userId);
13871        }
13872
13873        // Only system components can circumvent runtime permissions when installing.
13874        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
13875                && mContext.checkCallingOrSelfPermission(Manifest.permission
13876                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
13877            throw new SecurityException("You need the "
13878                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
13879                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
13880        }
13881
13882        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
13883                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13884            throw new IllegalArgumentException(
13885                    "New installs into ASEC containers no longer supported");
13886        }
13887
13888        final File originFile = new File(originPath);
13889        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
13890
13891        final Message msg = mHandler.obtainMessage(INIT_COPY);
13892        final VerificationInfo verificationInfo = new VerificationInfo(
13893                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
13894        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
13895                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
13896                null /*packageAbiOverride*/, null /*grantedPermissions*/,
13897                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
13898        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
13899        msg.obj = params;
13900
13901        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
13902                System.identityHashCode(msg.obj));
13903        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13904                System.identityHashCode(msg.obj));
13905
13906        mHandler.sendMessage(msg);
13907    }
13908
13909
13910    /**
13911     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13912     * it is acting on behalf on an enterprise or the user).
13913     *
13914     * Note that the ordering of the conditionals in this method is important. The checks we perform
13915     * are as follows, in this order:
13916     *
13917     * 1) If the install is being performed by a system app, we can trust the app to have set the
13918     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13919     *    what it is.
13920     * 2) If the install is being performed by a device or profile owner app, the install reason
13921     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13922     *    set the install reason correctly. If the app targets an older SDK version where install
13923     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13924     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13925     * 3) In all other cases, the install is being performed by a regular app that is neither part
13926     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13927     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13928     *    set to enterprise policy and if so, change it to unknown instead.
13929     */
13930    private int fixUpInstallReason(String installerPackageName, int installerUid,
13931            int installReason) {
13932        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13933                == PERMISSION_GRANTED) {
13934            // If the install is being performed by a system app, we trust that app to have set the
13935            // install reason correctly.
13936            return installReason;
13937        }
13938
13939        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13940            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13941        if (dpm != null) {
13942            ComponentName owner = null;
13943            try {
13944                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13945                if (owner == null) {
13946                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13947                }
13948            } catch (RemoteException e) {
13949            }
13950            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13951                // If the install is being performed by a device or profile owner, the install
13952                // reason should be enterprise policy.
13953                return PackageManager.INSTALL_REASON_POLICY;
13954            }
13955        }
13956
13957        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13958            // If the install is being performed by a regular app (i.e. neither system app nor
13959            // device or profile owner), we have no reason to believe that the app is acting on
13960            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13961            // change it to unknown instead.
13962            return PackageManager.INSTALL_REASON_UNKNOWN;
13963        }
13964
13965        // If the install is being performed by a regular app and the install reason was set to any
13966        // value but enterprise policy, leave the install reason unchanged.
13967        return installReason;
13968    }
13969
13970    void installStage(String packageName, File stagedDir,
13971            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13972            String installerPackageName, int installerUid, UserHandle user,
13973            Certificate[][] certificates) {
13974        if (DEBUG_EPHEMERAL) {
13975            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13976                Slog.d(TAG, "Ephemeral install of " + packageName);
13977            }
13978        }
13979        final VerificationInfo verificationInfo = new VerificationInfo(
13980                sessionParams.originatingUri, sessionParams.referrerUri,
13981                sessionParams.originatingUid, installerUid);
13982
13983        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13984
13985        final Message msg = mHandler.obtainMessage(INIT_COPY);
13986        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13987                sessionParams.installReason);
13988        final InstallParams params = new InstallParams(origin, null, observer,
13989                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13990                verificationInfo, user, sessionParams.abiOverride,
13991                sessionParams.grantedRuntimePermissions, certificates, installReason);
13992        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13993        msg.obj = params;
13994
13995        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13996                System.identityHashCode(msg.obj));
13997        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13998                System.identityHashCode(msg.obj));
13999
14000        mHandler.sendMessage(msg);
14001    }
14002
14003    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14004            int userId) {
14005        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14006        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
14007                false /*startReceiver*/, pkgSetting.appId, userId);
14008
14009        // Send a session commit broadcast
14010        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14011        info.installReason = pkgSetting.getInstallReason(userId);
14012        info.appPackageName = packageName;
14013        sendSessionCommitBroadcast(info, userId);
14014    }
14015
14016    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
14017            boolean includeStopped, int appId, int... userIds) {
14018        if (ArrayUtils.isEmpty(userIds)) {
14019            return;
14020        }
14021        Bundle extras = new Bundle(1);
14022        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14023        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14024
14025        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14026                packageName, extras, 0, null, null, userIds);
14027        if (sendBootCompleted) {
14028            mHandler.post(() -> {
14029                        for (int userId : userIds) {
14030                            sendBootCompletedBroadcastToSystemApp(
14031                                    packageName, includeStopped, userId);
14032                        }
14033                    }
14034            );
14035        }
14036    }
14037
14038    /**
14039     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14040     * automatically without needing an explicit launch.
14041     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14042     */
14043    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
14044            int userId) {
14045        // If user is not running, the app didn't miss any broadcast
14046        if (!mUserManagerInternal.isUserRunning(userId)) {
14047            return;
14048        }
14049        final IActivityManager am = ActivityManager.getService();
14050        try {
14051            // Deliver LOCKED_BOOT_COMPLETED first
14052            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14053                    .setPackage(packageName);
14054            if (includeStopped) {
14055                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14056            }
14057            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14058            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14059                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14060
14061            // Deliver BOOT_COMPLETED only if user is unlocked
14062            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14063                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14064                if (includeStopped) {
14065                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14066                }
14067                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14068                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14069            }
14070        } catch (RemoteException e) {
14071            throw e.rethrowFromSystemServer();
14072        }
14073    }
14074
14075    @Override
14076    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14077            int userId) {
14078        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14079        PackageSetting pkgSetting;
14080        final int callingUid = Binder.getCallingUid();
14081        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14082                true /* requireFullPermission */, true /* checkShell */,
14083                "setApplicationHiddenSetting for user " + userId);
14084
14085        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14086            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14087            return false;
14088        }
14089
14090        long callingId = Binder.clearCallingIdentity();
14091        try {
14092            boolean sendAdded = false;
14093            boolean sendRemoved = false;
14094            // writer
14095            synchronized (mPackages) {
14096                pkgSetting = mSettings.mPackages.get(packageName);
14097                if (pkgSetting == null) {
14098                    return false;
14099                }
14100                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14101                    return false;
14102                }
14103                // Do not allow "android" is being disabled
14104                if ("android".equals(packageName)) {
14105                    Slog.w(TAG, "Cannot hide package: android");
14106                    return false;
14107                }
14108                // Cannot hide static shared libs as they are considered
14109                // a part of the using app (emulating static linking). Also
14110                // static libs are installed always on internal storage.
14111                PackageParser.Package pkg = mPackages.get(packageName);
14112                if (pkg != null && pkg.staticSharedLibName != null) {
14113                    Slog.w(TAG, "Cannot hide package: " + packageName
14114                            + " providing static shared library: "
14115                            + pkg.staticSharedLibName);
14116                    return false;
14117                }
14118                // Only allow protected packages to hide themselves.
14119                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14120                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14121                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14122                    return false;
14123                }
14124
14125                if (pkgSetting.getHidden(userId) != hidden) {
14126                    pkgSetting.setHidden(hidden, userId);
14127                    mSettings.writePackageRestrictionsLPr(userId);
14128                    if (hidden) {
14129                        sendRemoved = true;
14130                    } else {
14131                        sendAdded = true;
14132                    }
14133                }
14134            }
14135            if (sendAdded) {
14136                sendPackageAddedForUser(packageName, pkgSetting, userId);
14137                return true;
14138            }
14139            if (sendRemoved) {
14140                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14141                        "hiding pkg");
14142                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14143                return true;
14144            }
14145        } finally {
14146            Binder.restoreCallingIdentity(callingId);
14147        }
14148        return false;
14149    }
14150
14151    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14152            int userId) {
14153        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14154        info.removedPackage = packageName;
14155        info.installerPackageName = pkgSetting.installerPackageName;
14156        info.removedUsers = new int[] {userId};
14157        info.broadcastUsers = new int[] {userId};
14158        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14159        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14160    }
14161
14162    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14163        if (pkgList.length > 0) {
14164            Bundle extras = new Bundle(1);
14165            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14166
14167            sendPackageBroadcast(
14168                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14169                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14170                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14171                    new int[] {userId});
14172        }
14173    }
14174
14175    /**
14176     * Returns true if application is not found or there was an error. Otherwise it returns
14177     * the hidden state of the package for the given user.
14178     */
14179    @Override
14180    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14181        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14182        final int callingUid = Binder.getCallingUid();
14183        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14184                true /* requireFullPermission */, false /* checkShell */,
14185                "getApplicationHidden for user " + userId);
14186        PackageSetting ps;
14187        long callingId = Binder.clearCallingIdentity();
14188        try {
14189            // writer
14190            synchronized (mPackages) {
14191                ps = mSettings.mPackages.get(packageName);
14192                if (ps == null) {
14193                    return true;
14194                }
14195                if (filterAppAccessLPr(ps, callingUid, userId)) {
14196                    return true;
14197                }
14198                return ps.getHidden(userId);
14199            }
14200        } finally {
14201            Binder.restoreCallingIdentity(callingId);
14202        }
14203    }
14204
14205    /**
14206     * @hide
14207     */
14208    @Override
14209    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14210            int installReason) {
14211        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14212                null);
14213        PackageSetting pkgSetting;
14214        final int callingUid = Binder.getCallingUid();
14215        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14216                true /* requireFullPermission */, true /* checkShell */,
14217                "installExistingPackage for user " + userId);
14218        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14219            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14220        }
14221
14222        long callingId = Binder.clearCallingIdentity();
14223        try {
14224            boolean installed = false;
14225            final boolean instantApp =
14226                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14227            final boolean fullApp =
14228                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14229
14230            // writer
14231            synchronized (mPackages) {
14232                pkgSetting = mSettings.mPackages.get(packageName);
14233                if (pkgSetting == null) {
14234                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14235                }
14236                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14237                    // only allow the existing package to be used if it's installed as a full
14238                    // application for at least one user
14239                    boolean installAllowed = false;
14240                    for (int checkUserId : sUserManager.getUserIds()) {
14241                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14242                        if (installAllowed) {
14243                            break;
14244                        }
14245                    }
14246                    if (!installAllowed) {
14247                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14248                    }
14249                }
14250                if (!pkgSetting.getInstalled(userId)) {
14251                    pkgSetting.setInstalled(true, userId);
14252                    pkgSetting.setHidden(false, userId);
14253                    pkgSetting.setInstallReason(installReason, userId);
14254                    mSettings.writePackageRestrictionsLPr(userId);
14255                    mSettings.writeKernelMappingLPr(pkgSetting);
14256                    installed = true;
14257                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14258                    // upgrade app from instant to full; we don't allow app downgrade
14259                    installed = true;
14260                }
14261                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14262            }
14263
14264            if (installed) {
14265                if (pkgSetting.pkg != null) {
14266                    synchronized (mInstallLock) {
14267                        // We don't need to freeze for a brand new install
14268                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14269                    }
14270                }
14271                sendPackageAddedForUser(packageName, pkgSetting, userId);
14272                synchronized (mPackages) {
14273                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14274                }
14275            }
14276        } finally {
14277            Binder.restoreCallingIdentity(callingId);
14278        }
14279
14280        return PackageManager.INSTALL_SUCCEEDED;
14281    }
14282
14283    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14284            boolean instantApp, boolean fullApp) {
14285        // no state specified; do nothing
14286        if (!instantApp && !fullApp) {
14287            return;
14288        }
14289        if (userId != UserHandle.USER_ALL) {
14290            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14291                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14292            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14293                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14294            }
14295        } else {
14296            for (int currentUserId : sUserManager.getUserIds()) {
14297                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14298                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14299                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14300                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14301                }
14302            }
14303        }
14304    }
14305
14306    boolean isUserRestricted(int userId, String restrictionKey) {
14307        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14308        if (restrictions.getBoolean(restrictionKey, false)) {
14309            Log.w(TAG, "User is restricted: " + restrictionKey);
14310            return true;
14311        }
14312        return false;
14313    }
14314
14315    @Override
14316    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14317            int userId) {
14318        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14319        final int callingUid = Binder.getCallingUid();
14320        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14321                true /* requireFullPermission */, true /* checkShell */,
14322                "setPackagesSuspended for user " + userId);
14323
14324        if (ArrayUtils.isEmpty(packageNames)) {
14325            return packageNames;
14326        }
14327
14328        // List of package names for whom the suspended state has changed.
14329        List<String> changedPackages = new ArrayList<>(packageNames.length);
14330        // List of package names for whom the suspended state is not set as requested in this
14331        // method.
14332        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14333        long callingId = Binder.clearCallingIdentity();
14334        try {
14335            for (int i = 0; i < packageNames.length; i++) {
14336                String packageName = packageNames[i];
14337                boolean changed = false;
14338                final int appId;
14339                synchronized (mPackages) {
14340                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14341                    if (pkgSetting == null
14342                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14343                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14344                                + "\". Skipping suspending/un-suspending.");
14345                        unactionedPackages.add(packageName);
14346                        continue;
14347                    }
14348                    appId = pkgSetting.appId;
14349                    if (pkgSetting.getSuspended(userId) != suspended) {
14350                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14351                            unactionedPackages.add(packageName);
14352                            continue;
14353                        }
14354                        pkgSetting.setSuspended(suspended, userId);
14355                        mSettings.writePackageRestrictionsLPr(userId);
14356                        changed = true;
14357                        changedPackages.add(packageName);
14358                    }
14359                }
14360
14361                if (changed && suspended) {
14362                    killApplication(packageName, UserHandle.getUid(userId, appId),
14363                            "suspending package");
14364                }
14365            }
14366        } finally {
14367            Binder.restoreCallingIdentity(callingId);
14368        }
14369
14370        if (!changedPackages.isEmpty()) {
14371            sendPackagesSuspendedForUser(changedPackages.toArray(
14372                    new String[changedPackages.size()]), userId, suspended);
14373        }
14374
14375        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14376    }
14377
14378    @Override
14379    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14380        final int callingUid = Binder.getCallingUid();
14381        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14382                true /* requireFullPermission */, false /* checkShell */,
14383                "isPackageSuspendedForUser for user " + userId);
14384        synchronized (mPackages) {
14385            final PackageSetting ps = mSettings.mPackages.get(packageName);
14386            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14387                throw new IllegalArgumentException("Unknown target package: " + packageName);
14388            }
14389            return ps.getSuspended(userId);
14390        }
14391    }
14392
14393    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14394        if (isPackageDeviceAdmin(packageName, userId)) {
14395            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14396                    + "\": has an active device admin");
14397            return false;
14398        }
14399
14400        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14401        if (packageName.equals(activeLauncherPackageName)) {
14402            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14403                    + "\": contains the active launcher");
14404            return false;
14405        }
14406
14407        if (packageName.equals(mRequiredInstallerPackage)) {
14408            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14409                    + "\": required for package installation");
14410            return false;
14411        }
14412
14413        if (packageName.equals(mRequiredUninstallerPackage)) {
14414            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14415                    + "\": required for package uninstallation");
14416            return false;
14417        }
14418
14419        if (packageName.equals(mRequiredVerifierPackage)) {
14420            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14421                    + "\": required for package verification");
14422            return false;
14423        }
14424
14425        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14426            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14427                    + "\": is the default dialer");
14428            return false;
14429        }
14430
14431        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14432            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14433                    + "\": protected package");
14434            return false;
14435        }
14436
14437        // Cannot suspend static shared libs as they are considered
14438        // a part of the using app (emulating static linking). Also
14439        // static libs are installed always on internal storage.
14440        PackageParser.Package pkg = mPackages.get(packageName);
14441        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14442            Slog.w(TAG, "Cannot suspend package: " + packageName
14443                    + " providing static shared library: "
14444                    + pkg.staticSharedLibName);
14445            return false;
14446        }
14447
14448        return true;
14449    }
14450
14451    private String getActiveLauncherPackageName(int userId) {
14452        Intent intent = new Intent(Intent.ACTION_MAIN);
14453        intent.addCategory(Intent.CATEGORY_HOME);
14454        ResolveInfo resolveInfo = resolveIntent(
14455                intent,
14456                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14457                PackageManager.MATCH_DEFAULT_ONLY,
14458                userId);
14459
14460        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14461    }
14462
14463    private String getDefaultDialerPackageName(int userId) {
14464        synchronized (mPackages) {
14465            return mSettings.getDefaultDialerPackageNameLPw(userId);
14466        }
14467    }
14468
14469    @Override
14470    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14471        mContext.enforceCallingOrSelfPermission(
14472                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14473                "Only package verification agents can verify applications");
14474
14475        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14476        final PackageVerificationResponse response = new PackageVerificationResponse(
14477                verificationCode, Binder.getCallingUid());
14478        msg.arg1 = id;
14479        msg.obj = response;
14480        mHandler.sendMessage(msg);
14481    }
14482
14483    @Override
14484    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14485            long millisecondsToDelay) {
14486        mContext.enforceCallingOrSelfPermission(
14487                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14488                "Only package verification agents can extend verification timeouts");
14489
14490        final PackageVerificationState state = mPendingVerification.get(id);
14491        final PackageVerificationResponse response = new PackageVerificationResponse(
14492                verificationCodeAtTimeout, Binder.getCallingUid());
14493
14494        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14495            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14496        }
14497        if (millisecondsToDelay < 0) {
14498            millisecondsToDelay = 0;
14499        }
14500        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14501                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14502            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14503        }
14504
14505        if ((state != null) && !state.timeoutExtended()) {
14506            state.extendTimeout();
14507
14508            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14509            msg.arg1 = id;
14510            msg.obj = response;
14511            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14512        }
14513    }
14514
14515    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14516            int verificationCode, UserHandle user) {
14517        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14518        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14519        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14520        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14521        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14522
14523        mContext.sendBroadcastAsUser(intent, user,
14524                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14525    }
14526
14527    private ComponentName matchComponentForVerifier(String packageName,
14528            List<ResolveInfo> receivers) {
14529        ActivityInfo targetReceiver = null;
14530
14531        final int NR = receivers.size();
14532        for (int i = 0; i < NR; i++) {
14533            final ResolveInfo info = receivers.get(i);
14534            if (info.activityInfo == null) {
14535                continue;
14536            }
14537
14538            if (packageName.equals(info.activityInfo.packageName)) {
14539                targetReceiver = info.activityInfo;
14540                break;
14541            }
14542        }
14543
14544        if (targetReceiver == null) {
14545            return null;
14546        }
14547
14548        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14549    }
14550
14551    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14552            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14553        if (pkgInfo.verifiers.length == 0) {
14554            return null;
14555        }
14556
14557        final int N = pkgInfo.verifiers.length;
14558        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14559        for (int i = 0; i < N; i++) {
14560            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14561
14562            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14563                    receivers);
14564            if (comp == null) {
14565                continue;
14566            }
14567
14568            final int verifierUid = getUidForVerifier(verifierInfo);
14569            if (verifierUid == -1) {
14570                continue;
14571            }
14572
14573            if (DEBUG_VERIFY) {
14574                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14575                        + " with the correct signature");
14576            }
14577            sufficientVerifiers.add(comp);
14578            verificationState.addSufficientVerifier(verifierUid);
14579        }
14580
14581        return sufficientVerifiers;
14582    }
14583
14584    private int getUidForVerifier(VerifierInfo verifierInfo) {
14585        synchronized (mPackages) {
14586            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14587            if (pkg == null) {
14588                return -1;
14589            } else if (pkg.mSignatures.length != 1) {
14590                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14591                        + " has more than one signature; ignoring");
14592                return -1;
14593            }
14594
14595            /*
14596             * If the public key of the package's signature does not match
14597             * our expected public key, then this is a different package and
14598             * we should skip.
14599             */
14600
14601            final byte[] expectedPublicKey;
14602            try {
14603                final Signature verifierSig = pkg.mSignatures[0];
14604                final PublicKey publicKey = verifierSig.getPublicKey();
14605                expectedPublicKey = publicKey.getEncoded();
14606            } catch (CertificateException e) {
14607                return -1;
14608            }
14609
14610            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14611
14612            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14613                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14614                        + " does not have the expected public key; ignoring");
14615                return -1;
14616            }
14617
14618            return pkg.applicationInfo.uid;
14619        }
14620    }
14621
14622    @Override
14623    public void finishPackageInstall(int token, boolean didLaunch) {
14624        enforceSystemOrRoot("Only the system is allowed to finish installs");
14625
14626        if (DEBUG_INSTALL) {
14627            Slog.v(TAG, "BM finishing package install for " + token);
14628        }
14629        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14630
14631        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14632        mHandler.sendMessage(msg);
14633    }
14634
14635    /**
14636     * Get the verification agent timeout.  Used for both the APK verifier and the
14637     * intent filter verifier.
14638     *
14639     * @return verification timeout in milliseconds
14640     */
14641    private long getVerificationTimeout() {
14642        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14643                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14644                DEFAULT_VERIFICATION_TIMEOUT);
14645    }
14646
14647    /**
14648     * Get the default verification agent response code.
14649     *
14650     * @return default verification response code
14651     */
14652    private int getDefaultVerificationResponse(UserHandle user) {
14653        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14654            return PackageManager.VERIFICATION_REJECT;
14655        }
14656        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14657                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14658                DEFAULT_VERIFICATION_RESPONSE);
14659    }
14660
14661    /**
14662     * Check whether or not package verification has been enabled.
14663     *
14664     * @return true if verification should be performed
14665     */
14666    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14667        if (!DEFAULT_VERIFY_ENABLE) {
14668            return false;
14669        }
14670
14671        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14672
14673        // Check if installing from ADB
14674        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14675            // Do not run verification in a test harness environment
14676            if (ActivityManager.isRunningInTestHarness()) {
14677                return false;
14678            }
14679            if (ensureVerifyAppsEnabled) {
14680                return true;
14681            }
14682            // Check if the developer does not want package verification for ADB installs
14683            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14684                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14685                return false;
14686            }
14687        } else {
14688            // only when not installed from ADB, skip verification for instant apps when
14689            // the installer and verifier are the same.
14690            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14691                if (mInstantAppInstallerActivity != null
14692                        && mInstantAppInstallerActivity.packageName.equals(
14693                                mRequiredVerifierPackage)) {
14694                    try {
14695                        mContext.getSystemService(AppOpsManager.class)
14696                                .checkPackage(installerUid, mRequiredVerifierPackage);
14697                        if (DEBUG_VERIFY) {
14698                            Slog.i(TAG, "disable verification for instant app");
14699                        }
14700                        return false;
14701                    } catch (SecurityException ignore) { }
14702                }
14703            }
14704        }
14705
14706        if (ensureVerifyAppsEnabled) {
14707            return true;
14708        }
14709
14710        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14711                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14712    }
14713
14714    @Override
14715    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14716            throws RemoteException {
14717        mContext.enforceCallingOrSelfPermission(
14718                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14719                "Only intentfilter verification agents can verify applications");
14720
14721        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14722        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14723                Binder.getCallingUid(), verificationCode, failedDomains);
14724        msg.arg1 = id;
14725        msg.obj = response;
14726        mHandler.sendMessage(msg);
14727    }
14728
14729    @Override
14730    public int getIntentVerificationStatus(String packageName, int userId) {
14731        final int callingUid = Binder.getCallingUid();
14732        if (UserHandle.getUserId(callingUid) != userId) {
14733            mContext.enforceCallingOrSelfPermission(
14734                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14735                    "getIntentVerificationStatus" + userId);
14736        }
14737        if (getInstantAppPackageName(callingUid) != null) {
14738            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14739        }
14740        synchronized (mPackages) {
14741            final PackageSetting ps = mSettings.mPackages.get(packageName);
14742            if (ps == null
14743                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14744                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14745            }
14746            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14747        }
14748    }
14749
14750    @Override
14751    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14752        mContext.enforceCallingOrSelfPermission(
14753                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14754
14755        boolean result = false;
14756        synchronized (mPackages) {
14757            final PackageSetting ps = mSettings.mPackages.get(packageName);
14758            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14759                return false;
14760            }
14761            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14762        }
14763        if (result) {
14764            scheduleWritePackageRestrictionsLocked(userId);
14765        }
14766        return result;
14767    }
14768
14769    @Override
14770    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14771            String packageName) {
14772        final int callingUid = Binder.getCallingUid();
14773        if (getInstantAppPackageName(callingUid) != null) {
14774            return ParceledListSlice.emptyList();
14775        }
14776        synchronized (mPackages) {
14777            final PackageSetting ps = mSettings.mPackages.get(packageName);
14778            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14779                return ParceledListSlice.emptyList();
14780            }
14781            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14782        }
14783    }
14784
14785    @Override
14786    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14787        if (TextUtils.isEmpty(packageName)) {
14788            return ParceledListSlice.emptyList();
14789        }
14790        final int callingUid = Binder.getCallingUid();
14791        final int callingUserId = UserHandle.getUserId(callingUid);
14792        synchronized (mPackages) {
14793            PackageParser.Package pkg = mPackages.get(packageName);
14794            if (pkg == null || pkg.activities == null) {
14795                return ParceledListSlice.emptyList();
14796            }
14797            if (pkg.mExtras == null) {
14798                return ParceledListSlice.emptyList();
14799            }
14800            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14801            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14802                return ParceledListSlice.emptyList();
14803            }
14804            final int count = pkg.activities.size();
14805            ArrayList<IntentFilter> result = new ArrayList<>();
14806            for (int n=0; n<count; n++) {
14807                PackageParser.Activity activity = pkg.activities.get(n);
14808                if (activity.intents != null && activity.intents.size() > 0) {
14809                    result.addAll(activity.intents);
14810                }
14811            }
14812            return new ParceledListSlice<>(result);
14813        }
14814    }
14815
14816    @Override
14817    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14818        mContext.enforceCallingOrSelfPermission(
14819                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14820        if (UserHandle.getCallingUserId() != userId) {
14821            mContext.enforceCallingOrSelfPermission(
14822                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14823        }
14824
14825        synchronized (mPackages) {
14826            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14827            if (packageName != null) {
14828                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14829                        packageName, userId);
14830            }
14831            return result;
14832        }
14833    }
14834
14835    @Override
14836    public String getDefaultBrowserPackageName(int userId) {
14837        if (UserHandle.getCallingUserId() != userId) {
14838            mContext.enforceCallingOrSelfPermission(
14839                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14840        }
14841        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14842            return null;
14843        }
14844        synchronized (mPackages) {
14845            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14846        }
14847    }
14848
14849    /**
14850     * Get the "allow unknown sources" setting.
14851     *
14852     * @return the current "allow unknown sources" setting
14853     */
14854    private int getUnknownSourcesSettings() {
14855        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14856                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14857                -1);
14858    }
14859
14860    @Override
14861    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14862        final int callingUid = Binder.getCallingUid();
14863        if (getInstantAppPackageName(callingUid) != null) {
14864            return;
14865        }
14866        // writer
14867        synchronized (mPackages) {
14868            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14869            if (targetPackageSetting == null
14870                    || filterAppAccessLPr(
14871                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14872                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14873            }
14874
14875            PackageSetting installerPackageSetting;
14876            if (installerPackageName != null) {
14877                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14878                if (installerPackageSetting == null) {
14879                    throw new IllegalArgumentException("Unknown installer package: "
14880                            + installerPackageName);
14881                }
14882            } else {
14883                installerPackageSetting = null;
14884            }
14885
14886            Signature[] callerSignature;
14887            Object obj = mSettings.getUserIdLPr(callingUid);
14888            if (obj != null) {
14889                if (obj instanceof SharedUserSetting) {
14890                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
14891                } else if (obj instanceof PackageSetting) {
14892                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
14893                } else {
14894                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14895                }
14896            } else {
14897                throw new SecurityException("Unknown calling UID: " + callingUid);
14898            }
14899
14900            // Verify: can't set installerPackageName to a package that is
14901            // not signed with the same cert as the caller.
14902            if (installerPackageSetting != null) {
14903                if (compareSignatures(callerSignature,
14904                        installerPackageSetting.signatures.mSignatures)
14905                        != PackageManager.SIGNATURE_MATCH) {
14906                    throw new SecurityException(
14907                            "Caller does not have same cert as new installer package "
14908                            + installerPackageName);
14909                }
14910            }
14911
14912            // Verify: if target already has an installer package, it must
14913            // be signed with the same cert as the caller.
14914            if (targetPackageSetting.installerPackageName != null) {
14915                PackageSetting setting = mSettings.mPackages.get(
14916                        targetPackageSetting.installerPackageName);
14917                // If the currently set package isn't valid, then it's always
14918                // okay to change it.
14919                if (setting != null) {
14920                    if (compareSignatures(callerSignature,
14921                            setting.signatures.mSignatures)
14922                            != PackageManager.SIGNATURE_MATCH) {
14923                        throw new SecurityException(
14924                                "Caller does not have same cert as old installer package "
14925                                + targetPackageSetting.installerPackageName);
14926                    }
14927                }
14928            }
14929
14930            // Okay!
14931            targetPackageSetting.installerPackageName = installerPackageName;
14932            if (installerPackageName != null) {
14933                mSettings.mInstallerPackages.add(installerPackageName);
14934            }
14935            scheduleWriteSettingsLocked();
14936        }
14937    }
14938
14939    @Override
14940    public void setApplicationCategoryHint(String packageName, int categoryHint,
14941            String callerPackageName) {
14942        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14943            throw new SecurityException("Instant applications don't have access to this method");
14944        }
14945        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14946                callerPackageName);
14947        synchronized (mPackages) {
14948            PackageSetting ps = mSettings.mPackages.get(packageName);
14949            if (ps == null) {
14950                throw new IllegalArgumentException("Unknown target package " + packageName);
14951            }
14952            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14953                throw new IllegalArgumentException("Unknown target package " + packageName);
14954            }
14955            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14956                throw new IllegalArgumentException("Calling package " + callerPackageName
14957                        + " is not installer for " + packageName);
14958            }
14959
14960            if (ps.categoryHint != categoryHint) {
14961                ps.categoryHint = categoryHint;
14962                scheduleWriteSettingsLocked();
14963            }
14964        }
14965    }
14966
14967    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14968        // Queue up an async operation since the package installation may take a little while.
14969        mHandler.post(new Runnable() {
14970            public void run() {
14971                mHandler.removeCallbacks(this);
14972                 // Result object to be returned
14973                PackageInstalledInfo res = new PackageInstalledInfo();
14974                res.setReturnCode(currentStatus);
14975                res.uid = -1;
14976                res.pkg = null;
14977                res.removedInfo = null;
14978                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14979                    args.doPreInstall(res.returnCode);
14980                    synchronized (mInstallLock) {
14981                        installPackageTracedLI(args, res);
14982                    }
14983                    args.doPostInstall(res.returnCode, res.uid);
14984                }
14985
14986                // A restore should be performed at this point if (a) the install
14987                // succeeded, (b) the operation is not an update, and (c) the new
14988                // package has not opted out of backup participation.
14989                final boolean update = res.removedInfo != null
14990                        && res.removedInfo.removedPackage != null;
14991                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14992                boolean doRestore = !update
14993                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14994
14995                // Set up the post-install work request bookkeeping.  This will be used
14996                // and cleaned up by the post-install event handling regardless of whether
14997                // there's a restore pass performed.  Token values are >= 1.
14998                int token;
14999                if (mNextInstallToken < 0) mNextInstallToken = 1;
15000                token = mNextInstallToken++;
15001
15002                PostInstallData data = new PostInstallData(args, res);
15003                mRunningInstalls.put(token, data);
15004                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15005
15006                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15007                    // Pass responsibility to the Backup Manager.  It will perform a
15008                    // restore if appropriate, then pass responsibility back to the
15009                    // Package Manager to run the post-install observer callbacks
15010                    // and broadcasts.
15011                    IBackupManager bm = IBackupManager.Stub.asInterface(
15012                            ServiceManager.getService(Context.BACKUP_SERVICE));
15013                    if (bm != null) {
15014                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15015                                + " to BM for possible restore");
15016                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15017                        try {
15018                            // TODO: http://b/22388012
15019                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15020                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15021                            } else {
15022                                doRestore = false;
15023                            }
15024                        } catch (RemoteException e) {
15025                            // can't happen; the backup manager is local
15026                        } catch (Exception e) {
15027                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15028                            doRestore = false;
15029                        }
15030                    } else {
15031                        Slog.e(TAG, "Backup Manager not found!");
15032                        doRestore = false;
15033                    }
15034                }
15035
15036                if (!doRestore) {
15037                    // No restore possible, or the Backup Manager was mysteriously not
15038                    // available -- just fire the post-install work request directly.
15039                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15040
15041                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15042
15043                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15044                    mHandler.sendMessage(msg);
15045                }
15046            }
15047        });
15048    }
15049
15050    /**
15051     * Callback from PackageSettings whenever an app is first transitioned out of the
15052     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15053     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15054     * here whether the app is the target of an ongoing install, and only send the
15055     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15056     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15057     * handling.
15058     */
15059    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15060        // Serialize this with the rest of the install-process message chain.  In the
15061        // restore-at-install case, this Runnable will necessarily run before the
15062        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15063        // are coherent.  In the non-restore case, the app has already completed install
15064        // and been launched through some other means, so it is not in a problematic
15065        // state for observers to see the FIRST_LAUNCH signal.
15066        mHandler.post(new Runnable() {
15067            @Override
15068            public void run() {
15069                for (int i = 0; i < mRunningInstalls.size(); i++) {
15070                    final PostInstallData data = mRunningInstalls.valueAt(i);
15071                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15072                        continue;
15073                    }
15074                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15075                        // right package; but is it for the right user?
15076                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15077                            if (userId == data.res.newUsers[uIndex]) {
15078                                if (DEBUG_BACKUP) {
15079                                    Slog.i(TAG, "Package " + pkgName
15080                                            + " being restored so deferring FIRST_LAUNCH");
15081                                }
15082                                return;
15083                            }
15084                        }
15085                    }
15086                }
15087                // didn't find it, so not being restored
15088                if (DEBUG_BACKUP) {
15089                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15090                }
15091                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15092            }
15093        });
15094    }
15095
15096    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15097        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15098                installerPkg, null, userIds);
15099    }
15100
15101    private abstract class HandlerParams {
15102        private static final int MAX_RETRIES = 4;
15103
15104        /**
15105         * Number of times startCopy() has been attempted and had a non-fatal
15106         * error.
15107         */
15108        private int mRetries = 0;
15109
15110        /** User handle for the user requesting the information or installation. */
15111        private final UserHandle mUser;
15112        String traceMethod;
15113        int traceCookie;
15114
15115        HandlerParams(UserHandle user) {
15116            mUser = user;
15117        }
15118
15119        UserHandle getUser() {
15120            return mUser;
15121        }
15122
15123        HandlerParams setTraceMethod(String traceMethod) {
15124            this.traceMethod = traceMethod;
15125            return this;
15126        }
15127
15128        HandlerParams setTraceCookie(int traceCookie) {
15129            this.traceCookie = traceCookie;
15130            return this;
15131        }
15132
15133        final boolean startCopy() {
15134            boolean res;
15135            try {
15136                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15137
15138                if (++mRetries > MAX_RETRIES) {
15139                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15140                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15141                    handleServiceError();
15142                    return false;
15143                } else {
15144                    handleStartCopy();
15145                    res = true;
15146                }
15147            } catch (RemoteException e) {
15148                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15149                mHandler.sendEmptyMessage(MCS_RECONNECT);
15150                res = false;
15151            }
15152            handleReturnCode();
15153            return res;
15154        }
15155
15156        final void serviceError() {
15157            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15158            handleServiceError();
15159            handleReturnCode();
15160        }
15161
15162        abstract void handleStartCopy() throws RemoteException;
15163        abstract void handleServiceError();
15164        abstract void handleReturnCode();
15165    }
15166
15167    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15168        for (File path : paths) {
15169            try {
15170                mcs.clearDirectory(path.getAbsolutePath());
15171            } catch (RemoteException e) {
15172            }
15173        }
15174    }
15175
15176    static class OriginInfo {
15177        /**
15178         * Location where install is coming from, before it has been
15179         * copied/renamed into place. This could be a single monolithic APK
15180         * file, or a cluster directory. This location may be untrusted.
15181         */
15182        final File file;
15183
15184        /**
15185         * Flag indicating that {@link #file} or {@link #cid} has already been
15186         * staged, meaning downstream users don't need to defensively copy the
15187         * contents.
15188         */
15189        final boolean staged;
15190
15191        /**
15192         * Flag indicating that {@link #file} or {@link #cid} is an already
15193         * installed app that is being moved.
15194         */
15195        final boolean existing;
15196
15197        final String resolvedPath;
15198        final File resolvedFile;
15199
15200        static OriginInfo fromNothing() {
15201            return new OriginInfo(null, false, false);
15202        }
15203
15204        static OriginInfo fromUntrustedFile(File file) {
15205            return new OriginInfo(file, false, false);
15206        }
15207
15208        static OriginInfo fromExistingFile(File file) {
15209            return new OriginInfo(file, false, true);
15210        }
15211
15212        static OriginInfo fromStagedFile(File file) {
15213            return new OriginInfo(file, true, false);
15214        }
15215
15216        private OriginInfo(File file, boolean staged, boolean existing) {
15217            this.file = file;
15218            this.staged = staged;
15219            this.existing = existing;
15220
15221            if (file != null) {
15222                resolvedPath = file.getAbsolutePath();
15223                resolvedFile = file;
15224            } else {
15225                resolvedPath = null;
15226                resolvedFile = null;
15227            }
15228        }
15229    }
15230
15231    static class MoveInfo {
15232        final int moveId;
15233        final String fromUuid;
15234        final String toUuid;
15235        final String packageName;
15236        final String dataAppName;
15237        final int appId;
15238        final String seinfo;
15239        final int targetSdkVersion;
15240
15241        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15242                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15243            this.moveId = moveId;
15244            this.fromUuid = fromUuid;
15245            this.toUuid = toUuid;
15246            this.packageName = packageName;
15247            this.dataAppName = dataAppName;
15248            this.appId = appId;
15249            this.seinfo = seinfo;
15250            this.targetSdkVersion = targetSdkVersion;
15251        }
15252    }
15253
15254    static class VerificationInfo {
15255        /** A constant used to indicate that a uid value is not present. */
15256        public static final int NO_UID = -1;
15257
15258        /** URI referencing where the package was downloaded from. */
15259        final Uri originatingUri;
15260
15261        /** HTTP referrer URI associated with the originatingURI. */
15262        final Uri referrer;
15263
15264        /** UID of the application that the install request originated from. */
15265        final int originatingUid;
15266
15267        /** UID of application requesting the install */
15268        final int installerUid;
15269
15270        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15271            this.originatingUri = originatingUri;
15272            this.referrer = referrer;
15273            this.originatingUid = originatingUid;
15274            this.installerUid = installerUid;
15275        }
15276    }
15277
15278    class InstallParams extends HandlerParams {
15279        final OriginInfo origin;
15280        final MoveInfo move;
15281        final IPackageInstallObserver2 observer;
15282        int installFlags;
15283        final String installerPackageName;
15284        final String volumeUuid;
15285        private InstallArgs mArgs;
15286        private int mRet;
15287        final String packageAbiOverride;
15288        final String[] grantedRuntimePermissions;
15289        final VerificationInfo verificationInfo;
15290        final Certificate[][] certificates;
15291        final int installReason;
15292
15293        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15294                int installFlags, String installerPackageName, String volumeUuid,
15295                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15296                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15297            super(user);
15298            this.origin = origin;
15299            this.move = move;
15300            this.observer = observer;
15301            this.installFlags = installFlags;
15302            this.installerPackageName = installerPackageName;
15303            this.volumeUuid = volumeUuid;
15304            this.verificationInfo = verificationInfo;
15305            this.packageAbiOverride = packageAbiOverride;
15306            this.grantedRuntimePermissions = grantedPermissions;
15307            this.certificates = certificates;
15308            this.installReason = installReason;
15309        }
15310
15311        @Override
15312        public String toString() {
15313            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15314                    + " file=" + origin.file + "}";
15315        }
15316
15317        private int installLocationPolicy(PackageInfoLite pkgLite) {
15318            String packageName = pkgLite.packageName;
15319            int installLocation = pkgLite.installLocation;
15320            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15321            // reader
15322            synchronized (mPackages) {
15323                // Currently installed package which the new package is attempting to replace or
15324                // null if no such package is installed.
15325                PackageParser.Package installedPkg = mPackages.get(packageName);
15326                // Package which currently owns the data which the new package will own if installed.
15327                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15328                // will be null whereas dataOwnerPkg will contain information about the package
15329                // which was uninstalled while keeping its data.
15330                PackageParser.Package dataOwnerPkg = installedPkg;
15331                if (dataOwnerPkg  == null) {
15332                    PackageSetting ps = mSettings.mPackages.get(packageName);
15333                    if (ps != null) {
15334                        dataOwnerPkg = ps.pkg;
15335                    }
15336                }
15337
15338                if (dataOwnerPkg != null) {
15339                    // If installed, the package will get access to data left on the device by its
15340                    // predecessor. As a security measure, this is permited only if this is not a
15341                    // version downgrade or if the predecessor package is marked as debuggable and
15342                    // a downgrade is explicitly requested.
15343                    //
15344                    // On debuggable platform builds, downgrades are permitted even for
15345                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15346                    // not offer security guarantees and thus it's OK to disable some security
15347                    // mechanisms to make debugging/testing easier on those builds. However, even on
15348                    // debuggable builds downgrades of packages are permitted only if requested via
15349                    // installFlags. This is because we aim to keep the behavior of debuggable
15350                    // platform builds as close as possible to the behavior of non-debuggable
15351                    // platform builds.
15352                    final boolean downgradeRequested =
15353                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15354                    final boolean packageDebuggable =
15355                                (dataOwnerPkg.applicationInfo.flags
15356                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15357                    final boolean downgradePermitted =
15358                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15359                    if (!downgradePermitted) {
15360                        try {
15361                            checkDowngrade(dataOwnerPkg, pkgLite);
15362                        } catch (PackageManagerException e) {
15363                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15364                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15365                        }
15366                    }
15367                }
15368
15369                if (installedPkg != null) {
15370                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15371                        // Check for updated system application.
15372                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15373                            if (onSd) {
15374                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15375                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15376                            }
15377                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15378                        } else {
15379                            if (onSd) {
15380                                // Install flag overrides everything.
15381                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15382                            }
15383                            // If current upgrade specifies particular preference
15384                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15385                                // Application explicitly specified internal.
15386                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15387                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15388                                // App explictly prefers external. Let policy decide
15389                            } else {
15390                                // Prefer previous location
15391                                if (isExternal(installedPkg)) {
15392                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15393                                }
15394                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15395                            }
15396                        }
15397                    } else {
15398                        // Invalid install. Return error code
15399                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15400                    }
15401                }
15402            }
15403            // All the special cases have been taken care of.
15404            // Return result based on recommended install location.
15405            if (onSd) {
15406                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15407            }
15408            return pkgLite.recommendedInstallLocation;
15409        }
15410
15411        /*
15412         * Invoke remote method to get package information and install
15413         * location values. Override install location based on default
15414         * policy if needed and then create install arguments based
15415         * on the install location.
15416         */
15417        public void handleStartCopy() throws RemoteException {
15418            int ret = PackageManager.INSTALL_SUCCEEDED;
15419
15420            // If we're already staged, we've firmly committed to an install location
15421            if (origin.staged) {
15422                if (origin.file != null) {
15423                    installFlags |= PackageManager.INSTALL_INTERNAL;
15424                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15425                } else {
15426                    throw new IllegalStateException("Invalid stage location");
15427                }
15428            }
15429
15430            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15431            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15432            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15433            PackageInfoLite pkgLite = null;
15434
15435            if (onInt && onSd) {
15436                // Check if both bits are set.
15437                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15438                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15439            } else if (onSd && ephemeral) {
15440                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15441                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15442            } else {
15443                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15444                        packageAbiOverride);
15445
15446                if (DEBUG_EPHEMERAL && ephemeral) {
15447                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15448                }
15449
15450                /*
15451                 * If we have too little free space, try to free cache
15452                 * before giving up.
15453                 */
15454                if (!origin.staged && pkgLite.recommendedInstallLocation
15455                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15456                    // TODO: focus freeing disk space on the target device
15457                    final StorageManager storage = StorageManager.from(mContext);
15458                    final long lowThreshold = storage.getStorageLowBytes(
15459                            Environment.getDataDirectory());
15460
15461                    final long sizeBytes = mContainerService.calculateInstalledSize(
15462                            origin.resolvedPath, packageAbiOverride);
15463
15464                    try {
15465                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15466                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15467                                installFlags, packageAbiOverride);
15468                    } catch (InstallerException e) {
15469                        Slog.w(TAG, "Failed to free cache", e);
15470                    }
15471
15472                    /*
15473                     * The cache free must have deleted the file we
15474                     * downloaded to install.
15475                     *
15476                     * TODO: fix the "freeCache" call to not delete
15477                     *       the file we care about.
15478                     */
15479                    if (pkgLite.recommendedInstallLocation
15480                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15481                        pkgLite.recommendedInstallLocation
15482                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15483                    }
15484                }
15485            }
15486
15487            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15488                int loc = pkgLite.recommendedInstallLocation;
15489                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15490                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15491                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15492                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15493                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15494                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15495                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15496                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15497                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15498                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15499                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15500                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15501                } else {
15502                    // Override with defaults if needed.
15503                    loc = installLocationPolicy(pkgLite);
15504                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15505                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15506                    } else if (!onSd && !onInt) {
15507                        // Override install location with flags
15508                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15509                            // Set the flag to install on external media.
15510                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15511                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15512                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15513                            if (DEBUG_EPHEMERAL) {
15514                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15515                            }
15516                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15517                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15518                                    |PackageManager.INSTALL_INTERNAL);
15519                        } else {
15520                            // Make sure the flag for installing on external
15521                            // media is unset
15522                            installFlags |= PackageManager.INSTALL_INTERNAL;
15523                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15524                        }
15525                    }
15526                }
15527            }
15528
15529            final InstallArgs args = createInstallArgs(this);
15530            mArgs = args;
15531
15532            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15533                // TODO: http://b/22976637
15534                // Apps installed for "all" users use the device owner to verify the app
15535                UserHandle verifierUser = getUser();
15536                if (verifierUser == UserHandle.ALL) {
15537                    verifierUser = UserHandle.SYSTEM;
15538                }
15539
15540                /*
15541                 * Determine if we have any installed package verifiers. If we
15542                 * do, then we'll defer to them to verify the packages.
15543                 */
15544                final int requiredUid = mRequiredVerifierPackage == null ? -1
15545                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15546                                verifierUser.getIdentifier());
15547                final int installerUid =
15548                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15549                if (!origin.existing && requiredUid != -1
15550                        && isVerificationEnabled(
15551                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15552                    final Intent verification = new Intent(
15553                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15554                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15555                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15556                            PACKAGE_MIME_TYPE);
15557                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15558
15559                    // Query all live verifiers based on current user state
15560                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15561                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15562                            false /*allowDynamicSplits*/);
15563
15564                    if (DEBUG_VERIFY) {
15565                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15566                                + verification.toString() + " with " + pkgLite.verifiers.length
15567                                + " optional verifiers");
15568                    }
15569
15570                    final int verificationId = mPendingVerificationToken++;
15571
15572                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15573
15574                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15575                            installerPackageName);
15576
15577                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15578                            installFlags);
15579
15580                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15581                            pkgLite.packageName);
15582
15583                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15584                            pkgLite.versionCode);
15585
15586                    if (verificationInfo != null) {
15587                        if (verificationInfo.originatingUri != null) {
15588                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15589                                    verificationInfo.originatingUri);
15590                        }
15591                        if (verificationInfo.referrer != null) {
15592                            verification.putExtra(Intent.EXTRA_REFERRER,
15593                                    verificationInfo.referrer);
15594                        }
15595                        if (verificationInfo.originatingUid >= 0) {
15596                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15597                                    verificationInfo.originatingUid);
15598                        }
15599                        if (verificationInfo.installerUid >= 0) {
15600                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15601                                    verificationInfo.installerUid);
15602                        }
15603                    }
15604
15605                    final PackageVerificationState verificationState = new PackageVerificationState(
15606                            requiredUid, args);
15607
15608                    mPendingVerification.append(verificationId, verificationState);
15609
15610                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15611                            receivers, verificationState);
15612
15613                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15614                    final long idleDuration = getVerificationTimeout();
15615
15616                    /*
15617                     * If any sufficient verifiers were listed in the package
15618                     * manifest, attempt to ask them.
15619                     */
15620                    if (sufficientVerifiers != null) {
15621                        final int N = sufficientVerifiers.size();
15622                        if (N == 0) {
15623                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15624                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15625                        } else {
15626                            for (int i = 0; i < N; i++) {
15627                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15628                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15629                                        verifierComponent.getPackageName(), idleDuration,
15630                                        verifierUser.getIdentifier(), false, "package verifier");
15631
15632                                final Intent sufficientIntent = new Intent(verification);
15633                                sufficientIntent.setComponent(verifierComponent);
15634                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15635                            }
15636                        }
15637                    }
15638
15639                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15640                            mRequiredVerifierPackage, receivers);
15641                    if (ret == PackageManager.INSTALL_SUCCEEDED
15642                            && mRequiredVerifierPackage != null) {
15643                        Trace.asyncTraceBegin(
15644                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15645                        /*
15646                         * Send the intent to the required verification agent,
15647                         * but only start the verification timeout after the
15648                         * target BroadcastReceivers have run.
15649                         */
15650                        verification.setComponent(requiredVerifierComponent);
15651                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15652                                mRequiredVerifierPackage, idleDuration,
15653                                verifierUser.getIdentifier(), false, "package verifier");
15654                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15655                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15656                                new BroadcastReceiver() {
15657                                    @Override
15658                                    public void onReceive(Context context, Intent intent) {
15659                                        final Message msg = mHandler
15660                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15661                                        msg.arg1 = verificationId;
15662                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15663                                    }
15664                                }, null, 0, null, null);
15665
15666                        /*
15667                         * We don't want the copy to proceed until verification
15668                         * succeeds, so null out this field.
15669                         */
15670                        mArgs = null;
15671                    }
15672                } else {
15673                    /*
15674                     * No package verification is enabled, so immediately start
15675                     * the remote call to initiate copy using temporary file.
15676                     */
15677                    ret = args.copyApk(mContainerService, true);
15678                }
15679            }
15680
15681            mRet = ret;
15682        }
15683
15684        @Override
15685        void handleReturnCode() {
15686            // If mArgs is null, then MCS couldn't be reached. When it
15687            // reconnects, it will try again to install. At that point, this
15688            // will succeed.
15689            if (mArgs != null) {
15690                processPendingInstall(mArgs, mRet);
15691            }
15692        }
15693
15694        @Override
15695        void handleServiceError() {
15696            mArgs = createInstallArgs(this);
15697            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15698        }
15699    }
15700
15701    private InstallArgs createInstallArgs(InstallParams params) {
15702        if (params.move != null) {
15703            return new MoveInstallArgs(params);
15704        } else {
15705            return new FileInstallArgs(params);
15706        }
15707    }
15708
15709    /**
15710     * Create args that describe an existing installed package. Typically used
15711     * when cleaning up old installs, or used as a move source.
15712     */
15713    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15714            String resourcePath, String[] instructionSets) {
15715        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15716    }
15717
15718    static abstract class InstallArgs {
15719        /** @see InstallParams#origin */
15720        final OriginInfo origin;
15721        /** @see InstallParams#move */
15722        final MoveInfo move;
15723
15724        final IPackageInstallObserver2 observer;
15725        // Always refers to PackageManager flags only
15726        final int installFlags;
15727        final String installerPackageName;
15728        final String volumeUuid;
15729        final UserHandle user;
15730        final String abiOverride;
15731        final String[] installGrantPermissions;
15732        /** If non-null, drop an async trace when the install completes */
15733        final String traceMethod;
15734        final int traceCookie;
15735        final Certificate[][] certificates;
15736        final int installReason;
15737
15738        // The list of instruction sets supported by this app. This is currently
15739        // only used during the rmdex() phase to clean up resources. We can get rid of this
15740        // if we move dex files under the common app path.
15741        /* nullable */ String[] instructionSets;
15742
15743        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15744                int installFlags, String installerPackageName, String volumeUuid,
15745                UserHandle user, String[] instructionSets,
15746                String abiOverride, String[] installGrantPermissions,
15747                String traceMethod, int traceCookie, Certificate[][] certificates,
15748                int installReason) {
15749            this.origin = origin;
15750            this.move = move;
15751            this.installFlags = installFlags;
15752            this.observer = observer;
15753            this.installerPackageName = installerPackageName;
15754            this.volumeUuid = volumeUuid;
15755            this.user = user;
15756            this.instructionSets = instructionSets;
15757            this.abiOverride = abiOverride;
15758            this.installGrantPermissions = installGrantPermissions;
15759            this.traceMethod = traceMethod;
15760            this.traceCookie = traceCookie;
15761            this.certificates = certificates;
15762            this.installReason = installReason;
15763        }
15764
15765        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15766        abstract int doPreInstall(int status);
15767
15768        /**
15769         * Rename package into final resting place. All paths on the given
15770         * scanned package should be updated to reflect the rename.
15771         */
15772        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15773        abstract int doPostInstall(int status, int uid);
15774
15775        /** @see PackageSettingBase#codePathString */
15776        abstract String getCodePath();
15777        /** @see PackageSettingBase#resourcePathString */
15778        abstract String getResourcePath();
15779
15780        // Need installer lock especially for dex file removal.
15781        abstract void cleanUpResourcesLI();
15782        abstract boolean doPostDeleteLI(boolean delete);
15783
15784        /**
15785         * Called before the source arguments are copied. This is used mostly
15786         * for MoveParams when it needs to read the source file to put it in the
15787         * destination.
15788         */
15789        int doPreCopy() {
15790            return PackageManager.INSTALL_SUCCEEDED;
15791        }
15792
15793        /**
15794         * Called after the source arguments are copied. This is used mostly for
15795         * MoveParams when it needs to read the source file to put it in the
15796         * destination.
15797         */
15798        int doPostCopy(int uid) {
15799            return PackageManager.INSTALL_SUCCEEDED;
15800        }
15801
15802        protected boolean isFwdLocked() {
15803            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15804        }
15805
15806        protected boolean isExternalAsec() {
15807            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15808        }
15809
15810        protected boolean isEphemeral() {
15811            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15812        }
15813
15814        UserHandle getUser() {
15815            return user;
15816        }
15817    }
15818
15819    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15820        if (!allCodePaths.isEmpty()) {
15821            if (instructionSets == null) {
15822                throw new IllegalStateException("instructionSet == null");
15823            }
15824            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15825            for (String codePath : allCodePaths) {
15826                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15827                    try {
15828                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15829                    } catch (InstallerException ignored) {
15830                    }
15831                }
15832            }
15833        }
15834    }
15835
15836    /**
15837     * Logic to handle installation of non-ASEC applications, including copying
15838     * and renaming logic.
15839     */
15840    class FileInstallArgs extends InstallArgs {
15841        private File codeFile;
15842        private File resourceFile;
15843
15844        // Example topology:
15845        // /data/app/com.example/base.apk
15846        // /data/app/com.example/split_foo.apk
15847        // /data/app/com.example/lib/arm/libfoo.so
15848        // /data/app/com.example/lib/arm64/libfoo.so
15849        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15850
15851        /** New install */
15852        FileInstallArgs(InstallParams params) {
15853            super(params.origin, params.move, params.observer, params.installFlags,
15854                    params.installerPackageName, params.volumeUuid,
15855                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15856                    params.grantedRuntimePermissions,
15857                    params.traceMethod, params.traceCookie, params.certificates,
15858                    params.installReason);
15859            if (isFwdLocked()) {
15860                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15861            }
15862        }
15863
15864        /** Existing install */
15865        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15866            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15867                    null, null, null, 0, null /*certificates*/,
15868                    PackageManager.INSTALL_REASON_UNKNOWN);
15869            this.codeFile = (codePath != null) ? new File(codePath) : null;
15870            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15871        }
15872
15873        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15874            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15875            try {
15876                return doCopyApk(imcs, temp);
15877            } finally {
15878                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15879            }
15880        }
15881
15882        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15883            if (origin.staged) {
15884                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15885                codeFile = origin.file;
15886                resourceFile = origin.file;
15887                return PackageManager.INSTALL_SUCCEEDED;
15888            }
15889
15890            try {
15891                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15892                final File tempDir =
15893                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15894                codeFile = tempDir;
15895                resourceFile = tempDir;
15896            } catch (IOException e) {
15897                Slog.w(TAG, "Failed to create copy file: " + e);
15898                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15899            }
15900
15901            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15902                @Override
15903                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15904                    if (!FileUtils.isValidExtFilename(name)) {
15905                        throw new IllegalArgumentException("Invalid filename: " + name);
15906                    }
15907                    try {
15908                        final File file = new File(codeFile, name);
15909                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15910                                O_RDWR | O_CREAT, 0644);
15911                        Os.chmod(file.getAbsolutePath(), 0644);
15912                        return new ParcelFileDescriptor(fd);
15913                    } catch (ErrnoException e) {
15914                        throw new RemoteException("Failed to open: " + e.getMessage());
15915                    }
15916                }
15917            };
15918
15919            int ret = PackageManager.INSTALL_SUCCEEDED;
15920            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15921            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15922                Slog.e(TAG, "Failed to copy package");
15923                return ret;
15924            }
15925
15926            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15927            NativeLibraryHelper.Handle handle = null;
15928            try {
15929                handle = NativeLibraryHelper.Handle.create(codeFile);
15930                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15931                        abiOverride);
15932            } catch (IOException e) {
15933                Slog.e(TAG, "Copying native libraries failed", e);
15934                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15935            } finally {
15936                IoUtils.closeQuietly(handle);
15937            }
15938
15939            return ret;
15940        }
15941
15942        int doPreInstall(int status) {
15943            if (status != PackageManager.INSTALL_SUCCEEDED) {
15944                cleanUp();
15945            }
15946            return status;
15947        }
15948
15949        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15950            if (status != PackageManager.INSTALL_SUCCEEDED) {
15951                cleanUp();
15952                return false;
15953            }
15954
15955            final File targetDir = codeFile.getParentFile();
15956            final File beforeCodeFile = codeFile;
15957            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15958
15959            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15960            try {
15961                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15962            } catch (ErrnoException e) {
15963                Slog.w(TAG, "Failed to rename", e);
15964                return false;
15965            }
15966
15967            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15968                Slog.w(TAG, "Failed to restorecon");
15969                return false;
15970            }
15971
15972            // Reflect the rename internally
15973            codeFile = afterCodeFile;
15974            resourceFile = afterCodeFile;
15975
15976            // Reflect the rename in scanned details
15977            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15978            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15979                    afterCodeFile, pkg.baseCodePath));
15980            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15981                    afterCodeFile, pkg.splitCodePaths));
15982
15983            // Reflect the rename in app info
15984            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15985            pkg.setApplicationInfoCodePath(pkg.codePath);
15986            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15987            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15988            pkg.setApplicationInfoResourcePath(pkg.codePath);
15989            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15990            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15991
15992            return true;
15993        }
15994
15995        int doPostInstall(int status, int uid) {
15996            if (status != PackageManager.INSTALL_SUCCEEDED) {
15997                cleanUp();
15998            }
15999            return status;
16000        }
16001
16002        @Override
16003        String getCodePath() {
16004            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16005        }
16006
16007        @Override
16008        String getResourcePath() {
16009            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16010        }
16011
16012        private boolean cleanUp() {
16013            if (codeFile == null || !codeFile.exists()) {
16014                return false;
16015            }
16016
16017            removeCodePathLI(codeFile);
16018
16019            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16020                resourceFile.delete();
16021            }
16022
16023            return true;
16024        }
16025
16026        void cleanUpResourcesLI() {
16027            // Try enumerating all code paths before deleting
16028            List<String> allCodePaths = Collections.EMPTY_LIST;
16029            if (codeFile != null && codeFile.exists()) {
16030                try {
16031                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16032                    allCodePaths = pkg.getAllCodePaths();
16033                } catch (PackageParserException e) {
16034                    // Ignored; we tried our best
16035                }
16036            }
16037
16038            cleanUp();
16039            removeDexFiles(allCodePaths, instructionSets);
16040        }
16041
16042        boolean doPostDeleteLI(boolean delete) {
16043            // XXX err, shouldn't we respect the delete flag?
16044            cleanUpResourcesLI();
16045            return true;
16046        }
16047    }
16048
16049    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16050            PackageManagerException {
16051        if (copyRet < 0) {
16052            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16053                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16054                throw new PackageManagerException(copyRet, message);
16055            }
16056        }
16057    }
16058
16059    /**
16060     * Extract the StorageManagerService "container ID" from the full code path of an
16061     * .apk.
16062     */
16063    static String cidFromCodePath(String fullCodePath) {
16064        int eidx = fullCodePath.lastIndexOf("/");
16065        String subStr1 = fullCodePath.substring(0, eidx);
16066        int sidx = subStr1.lastIndexOf("/");
16067        return subStr1.substring(sidx+1, eidx);
16068    }
16069
16070    /**
16071     * Logic to handle movement of existing installed applications.
16072     */
16073    class MoveInstallArgs extends InstallArgs {
16074        private File codeFile;
16075        private File resourceFile;
16076
16077        /** New install */
16078        MoveInstallArgs(InstallParams params) {
16079            super(params.origin, params.move, params.observer, params.installFlags,
16080                    params.installerPackageName, params.volumeUuid,
16081                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16082                    params.grantedRuntimePermissions,
16083                    params.traceMethod, params.traceCookie, params.certificates,
16084                    params.installReason);
16085        }
16086
16087        int copyApk(IMediaContainerService imcs, boolean temp) {
16088            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16089                    + move.fromUuid + " to " + move.toUuid);
16090            synchronized (mInstaller) {
16091                try {
16092                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16093                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16094                } catch (InstallerException e) {
16095                    Slog.w(TAG, "Failed to move app", e);
16096                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16097                }
16098            }
16099
16100            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16101            resourceFile = codeFile;
16102            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16103
16104            return PackageManager.INSTALL_SUCCEEDED;
16105        }
16106
16107        int doPreInstall(int status) {
16108            if (status != PackageManager.INSTALL_SUCCEEDED) {
16109                cleanUp(move.toUuid);
16110            }
16111            return status;
16112        }
16113
16114        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16115            if (status != PackageManager.INSTALL_SUCCEEDED) {
16116                cleanUp(move.toUuid);
16117                return false;
16118            }
16119
16120            // Reflect the move in app info
16121            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16122            pkg.setApplicationInfoCodePath(pkg.codePath);
16123            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16124            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16125            pkg.setApplicationInfoResourcePath(pkg.codePath);
16126            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16127            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16128
16129            return true;
16130        }
16131
16132        int doPostInstall(int status, int uid) {
16133            if (status == PackageManager.INSTALL_SUCCEEDED) {
16134                cleanUp(move.fromUuid);
16135            } else {
16136                cleanUp(move.toUuid);
16137            }
16138            return status;
16139        }
16140
16141        @Override
16142        String getCodePath() {
16143            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16144        }
16145
16146        @Override
16147        String getResourcePath() {
16148            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16149        }
16150
16151        private boolean cleanUp(String volumeUuid) {
16152            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16153                    move.dataAppName);
16154            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16155            final int[] userIds = sUserManager.getUserIds();
16156            synchronized (mInstallLock) {
16157                // Clean up both app data and code
16158                // All package moves are frozen until finished
16159                for (int userId : userIds) {
16160                    try {
16161                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16162                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16163                    } catch (InstallerException e) {
16164                        Slog.w(TAG, String.valueOf(e));
16165                    }
16166                }
16167                removeCodePathLI(codeFile);
16168            }
16169            return true;
16170        }
16171
16172        void cleanUpResourcesLI() {
16173            throw new UnsupportedOperationException();
16174        }
16175
16176        boolean doPostDeleteLI(boolean delete) {
16177            throw new UnsupportedOperationException();
16178        }
16179    }
16180
16181    static String getAsecPackageName(String packageCid) {
16182        int idx = packageCid.lastIndexOf("-");
16183        if (idx == -1) {
16184            return packageCid;
16185        }
16186        return packageCid.substring(0, idx);
16187    }
16188
16189    // Utility method used to create code paths based on package name and available index.
16190    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16191        String idxStr = "";
16192        int idx = 1;
16193        // Fall back to default value of idx=1 if prefix is not
16194        // part of oldCodePath
16195        if (oldCodePath != null) {
16196            String subStr = oldCodePath;
16197            // Drop the suffix right away
16198            if (suffix != null && subStr.endsWith(suffix)) {
16199                subStr = subStr.substring(0, subStr.length() - suffix.length());
16200            }
16201            // If oldCodePath already contains prefix find out the
16202            // ending index to either increment or decrement.
16203            int sidx = subStr.lastIndexOf(prefix);
16204            if (sidx != -1) {
16205                subStr = subStr.substring(sidx + prefix.length());
16206                if (subStr != null) {
16207                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16208                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16209                    }
16210                    try {
16211                        idx = Integer.parseInt(subStr);
16212                        if (idx <= 1) {
16213                            idx++;
16214                        } else {
16215                            idx--;
16216                        }
16217                    } catch(NumberFormatException e) {
16218                    }
16219                }
16220            }
16221        }
16222        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16223        return prefix + idxStr;
16224    }
16225
16226    private File getNextCodePath(File targetDir, String packageName) {
16227        File result;
16228        SecureRandom random = new SecureRandom();
16229        byte[] bytes = new byte[16];
16230        do {
16231            random.nextBytes(bytes);
16232            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16233            result = new File(targetDir, packageName + "-" + suffix);
16234        } while (result.exists());
16235        return result;
16236    }
16237
16238    // Utility method that returns the relative package path with respect
16239    // to the installation directory. Like say for /data/data/com.test-1.apk
16240    // string com.test-1 is returned.
16241    static String deriveCodePathName(String codePath) {
16242        if (codePath == null) {
16243            return null;
16244        }
16245        final File codeFile = new File(codePath);
16246        final String name = codeFile.getName();
16247        if (codeFile.isDirectory()) {
16248            return name;
16249        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16250            final int lastDot = name.lastIndexOf('.');
16251            return name.substring(0, lastDot);
16252        } else {
16253            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16254            return null;
16255        }
16256    }
16257
16258    static class PackageInstalledInfo {
16259        String name;
16260        int uid;
16261        // The set of users that originally had this package installed.
16262        int[] origUsers;
16263        // The set of users that now have this package installed.
16264        int[] newUsers;
16265        PackageParser.Package pkg;
16266        int returnCode;
16267        String returnMsg;
16268        String installerPackageName;
16269        PackageRemovedInfo removedInfo;
16270        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16271
16272        public void setError(int code, String msg) {
16273            setReturnCode(code);
16274            setReturnMessage(msg);
16275            Slog.w(TAG, msg);
16276        }
16277
16278        public void setError(String msg, PackageParserException e) {
16279            setReturnCode(e.error);
16280            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16281            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16282            for (int i = 0; i < childCount; i++) {
16283                addedChildPackages.valueAt(i).setError(msg, e);
16284            }
16285            Slog.w(TAG, msg, e);
16286        }
16287
16288        public void setError(String msg, PackageManagerException e) {
16289            returnCode = e.error;
16290            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16291            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16292            for (int i = 0; i < childCount; i++) {
16293                addedChildPackages.valueAt(i).setError(msg, e);
16294            }
16295            Slog.w(TAG, msg, e);
16296        }
16297
16298        public void setReturnCode(int returnCode) {
16299            this.returnCode = returnCode;
16300            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16301            for (int i = 0; i < childCount; i++) {
16302                addedChildPackages.valueAt(i).returnCode = returnCode;
16303            }
16304        }
16305
16306        private void setReturnMessage(String returnMsg) {
16307            this.returnMsg = returnMsg;
16308            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16309            for (int i = 0; i < childCount; i++) {
16310                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16311            }
16312        }
16313
16314        // In some error cases we want to convey more info back to the observer
16315        String origPackage;
16316        String origPermission;
16317    }
16318
16319    /*
16320     * Install a non-existing package.
16321     */
16322    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
16323            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
16324            PackageInstalledInfo res, int installReason) {
16325        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16326
16327        // Remember this for later, in case we need to rollback this install
16328        String pkgName = pkg.packageName;
16329
16330        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16331
16332        synchronized(mPackages) {
16333            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16334            if (renamedPackage != null) {
16335                // A package with the same name is already installed, though
16336                // it has been renamed to an older name.  The package we
16337                // are trying to install should be installed as an update to
16338                // the existing one, but that has not been requested, so bail.
16339                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16340                        + " without first uninstalling package running as "
16341                        + renamedPackage);
16342                return;
16343            }
16344            if (mPackages.containsKey(pkgName)) {
16345                // Don't allow installation over an existing package with the same name.
16346                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16347                        + " without first uninstalling.");
16348                return;
16349            }
16350        }
16351
16352        try {
16353            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
16354                    System.currentTimeMillis(), user);
16355
16356            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16357
16358            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16359                prepareAppDataAfterInstallLIF(newPackage);
16360
16361            } else {
16362                // Remove package from internal structures, but keep around any
16363                // data that might have already existed
16364                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16365                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16366            }
16367        } catch (PackageManagerException e) {
16368            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16369        }
16370
16371        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16372    }
16373
16374    private boolean shouldCheckUpgradeKeySetLP(PackageSettingBase oldPs, int scanFlags) {
16375        // Can't rotate keys during boot or if sharedUser.
16376        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.isSharedUser()
16377                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
16378            return false;
16379        }
16380        // app is using upgradeKeySets; make sure all are valid
16381        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16382        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
16383        for (int i = 0; i < upgradeKeySets.length; i++) {
16384            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
16385                Slog.wtf(TAG, "Package "
16386                         + (oldPs.name != null ? oldPs.name : "<null>")
16387                         + " contains upgrade-key-set reference to unknown key-set: "
16388                         + upgradeKeySets[i]
16389                         + " reverting to signatures check.");
16390                return false;
16391            }
16392        }
16393        return true;
16394    }
16395
16396    private boolean checkUpgradeKeySetLP(PackageSettingBase oldPS, PackageParser.Package newPkg) {
16397        // Upgrade keysets are being used.  Determine if new package has a superset of the
16398        // required keys.
16399        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
16400        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16401        for (int i = 0; i < upgradeKeySets.length; i++) {
16402            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
16403            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
16404                return true;
16405            }
16406        }
16407        return false;
16408    }
16409
16410    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16411        try (DigestInputStream digestStream =
16412                new DigestInputStream(new FileInputStream(file), digest)) {
16413            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16414        }
16415    }
16416
16417    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
16418            UserHandle user, String installerPackageName, PackageInstalledInfo res,
16419            int installReason) {
16420        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16421
16422        final PackageParser.Package oldPackage;
16423        final PackageSetting ps;
16424        final String pkgName = pkg.packageName;
16425        final int[] allUsers;
16426        final int[] installedUsers;
16427
16428        synchronized(mPackages) {
16429            oldPackage = mPackages.get(pkgName);
16430            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16431
16432            // don't allow upgrade to target a release SDK from a pre-release SDK
16433            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16434                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16435            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16436                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16437            if (oldTargetsPreRelease
16438                    && !newTargetsPreRelease
16439                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16440                Slog.w(TAG, "Can't install package targeting released sdk");
16441                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16442                return;
16443            }
16444
16445            ps = mSettings.mPackages.get(pkgName);
16446
16447            // verify signatures are valid
16448            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
16449                if (!checkUpgradeKeySetLP(ps, pkg)) {
16450                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16451                            "New package not signed by keys specified by upgrade-keysets: "
16452                                    + pkgName);
16453                    return;
16454                }
16455            } else {
16456                // default to original signature matching
16457                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
16458                        != PackageManager.SIGNATURE_MATCH) {
16459                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16460                            "New package has a different signature: " + pkgName);
16461                    return;
16462                }
16463            }
16464
16465            // don't allow a system upgrade unless the upgrade hash matches
16466            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
16467                byte[] digestBytes = null;
16468                try {
16469                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16470                    updateDigest(digest, new File(pkg.baseCodePath));
16471                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16472                        for (String path : pkg.splitCodePaths) {
16473                            updateDigest(digest, new File(path));
16474                        }
16475                    }
16476                    digestBytes = digest.digest();
16477                } catch (NoSuchAlgorithmException | IOException e) {
16478                    res.setError(INSTALL_FAILED_INVALID_APK,
16479                            "Could not compute hash: " + pkgName);
16480                    return;
16481                }
16482                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16483                    res.setError(INSTALL_FAILED_INVALID_APK,
16484                            "New package fails restrict-update check: " + pkgName);
16485                    return;
16486                }
16487                // retain upgrade restriction
16488                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16489            }
16490
16491            // Check for shared user id changes
16492            String invalidPackageName =
16493                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16494            if (invalidPackageName != null) {
16495                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16496                        "Package " + invalidPackageName + " tried to change user "
16497                                + oldPackage.mSharedUserId);
16498                return;
16499            }
16500
16501            // In case of rollback, remember per-user/profile install state
16502            allUsers = sUserManager.getUserIds();
16503            installedUsers = ps.queryInstalledUsers(allUsers, true);
16504
16505            // don't allow an upgrade from full to ephemeral
16506            if (isInstantApp) {
16507                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16508                    for (int currentUser : allUsers) {
16509                        if (!ps.getInstantApp(currentUser)) {
16510                            // can't downgrade from full to instant
16511                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16512                                    + " for user: " + currentUser);
16513                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16514                            return;
16515                        }
16516                    }
16517                } else if (!ps.getInstantApp(user.getIdentifier())) {
16518                    // can't downgrade from full to instant
16519                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16520                            + " for user: " + user.getIdentifier());
16521                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16522                    return;
16523                }
16524            }
16525        }
16526
16527        // Update what is removed
16528        res.removedInfo = new PackageRemovedInfo(this);
16529        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16530        res.removedInfo.removedPackage = oldPackage.packageName;
16531        res.removedInfo.installerPackageName = ps.installerPackageName;
16532        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16533        res.removedInfo.isUpdate = true;
16534        res.removedInfo.origUsers = installedUsers;
16535        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16536        for (int i = 0; i < installedUsers.length; i++) {
16537            final int userId = installedUsers[i];
16538            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16539        }
16540
16541        final int childCount = (oldPackage.childPackages != null)
16542                ? oldPackage.childPackages.size() : 0;
16543        for (int i = 0; i < childCount; i++) {
16544            boolean childPackageUpdated = false;
16545            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16546            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16547            if (res.addedChildPackages != null) {
16548                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16549                if (childRes != null) {
16550                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16551                    childRes.removedInfo.removedPackage = childPkg.packageName;
16552                    if (childPs != null) {
16553                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16554                    }
16555                    childRes.removedInfo.isUpdate = true;
16556                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16557                    childPackageUpdated = true;
16558                }
16559            }
16560            if (!childPackageUpdated) {
16561                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16562                childRemovedRes.removedPackage = childPkg.packageName;
16563                if (childPs != null) {
16564                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16565                }
16566                childRemovedRes.isUpdate = false;
16567                childRemovedRes.dataRemoved = true;
16568                synchronized (mPackages) {
16569                    if (childPs != null) {
16570                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16571                    }
16572                }
16573                if (res.removedInfo.removedChildPackages == null) {
16574                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16575                }
16576                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16577            }
16578        }
16579
16580        boolean sysPkg = (isSystemApp(oldPackage));
16581        if (sysPkg) {
16582            // Set the system/privileged/oem flags as needed
16583            final boolean privileged =
16584                    (oldPackage.applicationInfo.privateFlags
16585                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16586            final boolean oem =
16587                    (oldPackage.applicationInfo.privateFlags
16588                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16589            final int systemPolicyFlags = policyFlags
16590                    | PackageParser.PARSE_IS_SYSTEM
16591                    | (privileged ? PARSE_IS_PRIVILEGED : 0)
16592                    | (oem ? PARSE_IS_OEM : 0);
16593
16594            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
16595                    user, allUsers, installerPackageName, res, installReason);
16596        } else {
16597            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
16598                    user, allUsers, installerPackageName, res, installReason);
16599        }
16600    }
16601
16602    @Override
16603    public List<String> getPreviousCodePaths(String packageName) {
16604        final int callingUid = Binder.getCallingUid();
16605        final List<String> result = new ArrayList<>();
16606        if (getInstantAppPackageName(callingUid) != null) {
16607            return result;
16608        }
16609        final PackageSetting ps = mSettings.mPackages.get(packageName);
16610        if (ps != null
16611                && ps.oldCodePaths != null
16612                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
16613            result.addAll(ps.oldCodePaths);
16614        }
16615        return result;
16616    }
16617
16618    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16619            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16620            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16621            int installReason) {
16622        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16623                + deletedPackage);
16624
16625        String pkgName = deletedPackage.packageName;
16626        boolean deletedPkg = true;
16627        boolean addedPkg = false;
16628        boolean updatedSettings = false;
16629        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16630        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16631                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16632
16633        final long origUpdateTime = (pkg.mExtras != null)
16634                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16635
16636        // First delete the existing package while retaining the data directory
16637        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16638                res.removedInfo, true, pkg)) {
16639            // If the existing package wasn't successfully deleted
16640            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16641            deletedPkg = false;
16642        } else {
16643            // Successfully deleted the old package; proceed with replace.
16644
16645            // If deleted package lived in a container, give users a chance to
16646            // relinquish resources before killing.
16647            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16648                if (DEBUG_INSTALL) {
16649                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16650                }
16651                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16652                final ArrayList<String> pkgList = new ArrayList<String>(1);
16653                pkgList.add(deletedPackage.applicationInfo.packageName);
16654                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16655            }
16656
16657            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16658                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16659            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16660
16661            try {
16662                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
16663                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16664                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16665                        installReason);
16666
16667                // Update the in-memory copy of the previous code paths.
16668                PackageSetting ps = mSettings.mPackages.get(pkgName);
16669                if (!killApp) {
16670                    if (ps.oldCodePaths == null) {
16671                        ps.oldCodePaths = new ArraySet<>();
16672                    }
16673                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16674                    if (deletedPackage.splitCodePaths != null) {
16675                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16676                    }
16677                } else {
16678                    ps.oldCodePaths = null;
16679                }
16680                if (ps.childPackageNames != null) {
16681                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16682                        final String childPkgName = ps.childPackageNames.get(i);
16683                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16684                        childPs.oldCodePaths = ps.oldCodePaths;
16685                    }
16686                }
16687                // set instant app status, but, only if it's explicitly specified
16688                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16689                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16690                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16691                prepareAppDataAfterInstallLIF(newPackage);
16692                addedPkg = true;
16693                mDexManager.notifyPackageUpdated(newPackage.packageName,
16694                        newPackage.baseCodePath, newPackage.splitCodePaths);
16695            } catch (PackageManagerException e) {
16696                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16697            }
16698        }
16699
16700        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16701            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16702
16703            // Revert all internal state mutations and added folders for the failed install
16704            if (addedPkg) {
16705                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16706                        res.removedInfo, true, null);
16707            }
16708
16709            // Restore the old package
16710            if (deletedPkg) {
16711                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16712                File restoreFile = new File(deletedPackage.codePath);
16713                // Parse old package
16714                boolean oldExternal = isExternal(deletedPackage);
16715                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16716                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16717                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16718                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16719                try {
16720                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16721                            null);
16722                } catch (PackageManagerException e) {
16723                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16724                            + e.getMessage());
16725                    return;
16726                }
16727
16728                synchronized (mPackages) {
16729                    // Ensure the installer package name up to date
16730                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16731
16732                    // Update permissions for restored package
16733                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16734
16735                    mSettings.writeLPr();
16736                }
16737
16738                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16739            }
16740        } else {
16741            synchronized (mPackages) {
16742                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16743                if (ps != null) {
16744                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16745                    if (res.removedInfo.removedChildPackages != null) {
16746                        final int childCount = res.removedInfo.removedChildPackages.size();
16747                        // Iterate in reverse as we may modify the collection
16748                        for (int i = childCount - 1; i >= 0; i--) {
16749                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16750                            if (res.addedChildPackages.containsKey(childPackageName)) {
16751                                res.removedInfo.removedChildPackages.removeAt(i);
16752                            } else {
16753                                PackageRemovedInfo childInfo = res.removedInfo
16754                                        .removedChildPackages.valueAt(i);
16755                                childInfo.removedForAllUsers = mPackages.get(
16756                                        childInfo.removedPackage) == null;
16757                            }
16758                        }
16759                    }
16760                }
16761            }
16762        }
16763    }
16764
16765    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16766            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16767            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16768            int installReason) {
16769        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16770                + ", old=" + deletedPackage);
16771
16772        final boolean disabledSystem;
16773
16774        // Remove existing system package
16775        removePackageLI(deletedPackage, true);
16776
16777        synchronized (mPackages) {
16778            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16779        }
16780        if (!disabledSystem) {
16781            // We didn't need to disable the .apk as a current system package,
16782            // which means we are replacing another update that is already
16783            // installed.  We need to make sure to delete the older one's .apk.
16784            res.removedInfo.args = createInstallArgsForExisting(0,
16785                    deletedPackage.applicationInfo.getCodePath(),
16786                    deletedPackage.applicationInfo.getResourcePath(),
16787                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16788        } else {
16789            res.removedInfo.args = null;
16790        }
16791
16792        // Successfully disabled the old package. Now proceed with re-installation
16793        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16794                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16795        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16796
16797        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16798        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16799                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16800
16801        PackageParser.Package newPackage = null;
16802        try {
16803            // Add the package to the internal data structures
16804            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16805
16806            // Set the update and install times
16807            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16808            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16809                    System.currentTimeMillis());
16810
16811            // Update the package dynamic state if succeeded
16812            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16813                // Now that the install succeeded make sure we remove data
16814                // directories for any child package the update removed.
16815                final int deletedChildCount = (deletedPackage.childPackages != null)
16816                        ? deletedPackage.childPackages.size() : 0;
16817                final int newChildCount = (newPackage.childPackages != null)
16818                        ? newPackage.childPackages.size() : 0;
16819                for (int i = 0; i < deletedChildCount; i++) {
16820                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16821                    boolean childPackageDeleted = true;
16822                    for (int j = 0; j < newChildCount; j++) {
16823                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16824                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16825                            childPackageDeleted = false;
16826                            break;
16827                        }
16828                    }
16829                    if (childPackageDeleted) {
16830                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16831                                deletedChildPkg.packageName);
16832                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16833                            PackageRemovedInfo removedChildRes = res.removedInfo
16834                                    .removedChildPackages.get(deletedChildPkg.packageName);
16835                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16836                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16837                        }
16838                    }
16839                }
16840
16841                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16842                        installReason);
16843                prepareAppDataAfterInstallLIF(newPackage);
16844
16845                mDexManager.notifyPackageUpdated(newPackage.packageName,
16846                            newPackage.baseCodePath, newPackage.splitCodePaths);
16847            }
16848        } catch (PackageManagerException e) {
16849            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16850            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16851        }
16852
16853        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16854            // Re installation failed. Restore old information
16855            // Remove new pkg information
16856            if (newPackage != null) {
16857                removeInstalledPackageLI(newPackage, true);
16858            }
16859            // Add back the old system package
16860            try {
16861                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16862            } catch (PackageManagerException e) {
16863                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16864            }
16865
16866            synchronized (mPackages) {
16867                if (disabledSystem) {
16868                    enableSystemPackageLPw(deletedPackage);
16869                }
16870
16871                // Ensure the installer package name up to date
16872                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16873
16874                // Update permissions for restored package
16875                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16876
16877                mSettings.writeLPr();
16878            }
16879
16880            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16881                    + " after failed upgrade");
16882        }
16883    }
16884
16885    /**
16886     * Checks whether the parent or any of the child packages have a change shared
16887     * user. For a package to be a valid update the shred users of the parent and
16888     * the children should match. We may later support changing child shared users.
16889     * @param oldPkg The updated package.
16890     * @param newPkg The update package.
16891     * @return The shared user that change between the versions.
16892     */
16893    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16894            PackageParser.Package newPkg) {
16895        // Check parent shared user
16896        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16897            return newPkg.packageName;
16898        }
16899        // Check child shared users
16900        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16901        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16902        for (int i = 0; i < newChildCount; i++) {
16903            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16904            // If this child was present, did it have the same shared user?
16905            for (int j = 0; j < oldChildCount; j++) {
16906                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16907                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16908                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16909                    return newChildPkg.packageName;
16910                }
16911            }
16912        }
16913        return null;
16914    }
16915
16916    private void removeNativeBinariesLI(PackageSetting ps) {
16917        // Remove the lib path for the parent package
16918        if (ps != null) {
16919            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16920            // Remove the lib path for the child packages
16921            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16922            for (int i = 0; i < childCount; i++) {
16923                PackageSetting childPs = null;
16924                synchronized (mPackages) {
16925                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16926                }
16927                if (childPs != null) {
16928                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16929                            .legacyNativeLibraryPathString);
16930                }
16931            }
16932        }
16933    }
16934
16935    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16936        // Enable the parent package
16937        mSettings.enableSystemPackageLPw(pkg.packageName);
16938        // Enable the child packages
16939        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16940        for (int i = 0; i < childCount; i++) {
16941            PackageParser.Package childPkg = pkg.childPackages.get(i);
16942            mSettings.enableSystemPackageLPw(childPkg.packageName);
16943        }
16944    }
16945
16946    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16947            PackageParser.Package newPkg) {
16948        // Disable the parent package (parent always replaced)
16949        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16950        // Disable the child packages
16951        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16952        for (int i = 0; i < childCount; i++) {
16953            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16954            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16955            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16956        }
16957        return disabled;
16958    }
16959
16960    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16961            String installerPackageName) {
16962        // Enable the parent package
16963        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16964        // Enable the child packages
16965        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16966        for (int i = 0; i < childCount; i++) {
16967            PackageParser.Package childPkg = pkg.childPackages.get(i);
16968            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16969        }
16970    }
16971
16972    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16973            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16974        // Update the parent package setting
16975        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16976                res, user, installReason);
16977        // Update the child packages setting
16978        final int childCount = (newPackage.childPackages != null)
16979                ? newPackage.childPackages.size() : 0;
16980        for (int i = 0; i < childCount; i++) {
16981            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16982            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16983            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16984                    childRes.origUsers, childRes, user, installReason);
16985        }
16986    }
16987
16988    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16989            String installerPackageName, int[] allUsers, int[] installedForUsers,
16990            PackageInstalledInfo res, UserHandle user, int installReason) {
16991        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16992
16993        String pkgName = newPackage.packageName;
16994        synchronized (mPackages) {
16995            //write settings. the installStatus will be incomplete at this stage.
16996            //note that the new package setting would have already been
16997            //added to mPackages. It hasn't been persisted yet.
16998            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16999            // TODO: Remove this write? It's also written at the end of this method
17000            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17001            mSettings.writeLPr();
17002            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17003        }
17004
17005        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17006        synchronized (mPackages) {
17007            updatePermissionsLPw(newPackage.packageName, newPackage,
17008                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17009                            ? UPDATE_PERMISSIONS_ALL : 0));
17010            // For system-bundled packages, we assume that installing an upgraded version
17011            // of the package implies that the user actually wants to run that new code,
17012            // so we enable the package.
17013            PackageSetting ps = mSettings.mPackages.get(pkgName);
17014            final int userId = user.getIdentifier();
17015            if (ps != null) {
17016                if (isSystemApp(newPackage)) {
17017                    if (DEBUG_INSTALL) {
17018                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17019                    }
17020                    // Enable system package for requested users
17021                    if (res.origUsers != null) {
17022                        for (int origUserId : res.origUsers) {
17023                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
17024                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17025                                        origUserId, installerPackageName);
17026                            }
17027                        }
17028                    }
17029                    // Also convey the prior install/uninstall state
17030                    if (allUsers != null && installedForUsers != null) {
17031                        for (int currentUserId : allUsers) {
17032                            final boolean installed = ArrayUtils.contains(
17033                                    installedForUsers, currentUserId);
17034                            if (DEBUG_INSTALL) {
17035                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
17036                            }
17037                            ps.setInstalled(installed, currentUserId);
17038                        }
17039                        // these install state changes will be persisted in the
17040                        // upcoming call to mSettings.writeLPr().
17041                    }
17042                }
17043                // It's implied that when a user requests installation, they want the app to be
17044                // installed and enabled.
17045                if (userId != UserHandle.USER_ALL) {
17046                    ps.setInstalled(true, userId);
17047                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17048                }
17049
17050                // When replacing an existing package, preserve the original install reason for all
17051                // users that had the package installed before.
17052                final Set<Integer> previousUserIds = new ArraySet<>();
17053                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17054                    final int installReasonCount = res.removedInfo.installReasons.size();
17055                    for (int i = 0; i < installReasonCount; i++) {
17056                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17057                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17058                        ps.setInstallReason(previousInstallReason, previousUserId);
17059                        previousUserIds.add(previousUserId);
17060                    }
17061                }
17062
17063                // Set install reason for users that are having the package newly installed.
17064                if (userId == UserHandle.USER_ALL) {
17065                    for (int currentUserId : sUserManager.getUserIds()) {
17066                        if (!previousUserIds.contains(currentUserId)) {
17067                            ps.setInstallReason(installReason, currentUserId);
17068                        }
17069                    }
17070                } else if (!previousUserIds.contains(userId)) {
17071                    ps.setInstallReason(installReason, userId);
17072                }
17073                mSettings.writeKernelMappingLPr(ps);
17074            }
17075            res.name = pkgName;
17076            res.uid = newPackage.applicationInfo.uid;
17077            res.pkg = newPackage;
17078            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17079            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17080            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17081            //to update install status
17082            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17083            mSettings.writeLPr();
17084            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17085        }
17086
17087        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17088    }
17089
17090    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17091        try {
17092            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17093            installPackageLI(args, res);
17094        } finally {
17095            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17096        }
17097    }
17098
17099    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17100        final int installFlags = args.installFlags;
17101        final String installerPackageName = args.installerPackageName;
17102        final String volumeUuid = args.volumeUuid;
17103        final File tmpPackageFile = new File(args.getCodePath());
17104        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17105        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17106                || (args.volumeUuid != null));
17107        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17108        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17109        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17110        final boolean virtualPreload =
17111                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
17112        boolean replace = false;
17113        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17114        if (args.move != null) {
17115            // moving a complete application; perform an initial scan on the new install location
17116            scanFlags |= SCAN_INITIAL;
17117        }
17118        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17119            scanFlags |= SCAN_DONT_KILL_APP;
17120        }
17121        if (instantApp) {
17122            scanFlags |= SCAN_AS_INSTANT_APP;
17123        }
17124        if (fullApp) {
17125            scanFlags |= SCAN_AS_FULL_APP;
17126        }
17127        if (virtualPreload) {
17128            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
17129        }
17130
17131        // Result object to be returned
17132        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17133        res.installerPackageName = installerPackageName;
17134
17135        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17136
17137        // Sanity check
17138        if (instantApp && (forwardLocked || onExternal)) {
17139            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17140                    + " external=" + onExternal);
17141            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17142            return;
17143        }
17144
17145        // Retrieve PackageSettings and parse package
17146        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17147                | PackageParser.PARSE_ENFORCE_CODE
17148                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17149                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17150                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17151                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17152        PackageParser pp = new PackageParser();
17153        pp.setSeparateProcesses(mSeparateProcesses);
17154        pp.setDisplayMetrics(mMetrics);
17155        pp.setCallback(mPackageParserCallback);
17156
17157        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17158        final PackageParser.Package pkg;
17159        try {
17160            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17161        } catch (PackageParserException e) {
17162            res.setError("Failed parse during installPackageLI", e);
17163            return;
17164        } finally {
17165            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17166        }
17167
17168        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17169        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17170            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
17171            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17172                    "Instant app package must target O");
17173            return;
17174        }
17175        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17176            Slog.w(TAG, "Instant app package " + pkg.packageName
17177                    + " does not target targetSandboxVersion 2");
17178            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17179                    "Instant app package must use targetSanboxVersion 2");
17180            return;
17181        }
17182
17183        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17184            // Static shared libraries have synthetic package names
17185            renameStaticSharedLibraryPackage(pkg);
17186
17187            // No static shared libs on external storage
17188            if (onExternal) {
17189                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17190                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17191                        "Packages declaring static-shared libs cannot be updated");
17192                return;
17193            }
17194        }
17195
17196        // If we are installing a clustered package add results for the children
17197        if (pkg.childPackages != null) {
17198            synchronized (mPackages) {
17199                final int childCount = pkg.childPackages.size();
17200                for (int i = 0; i < childCount; i++) {
17201                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17202                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17203                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17204                    childRes.pkg = childPkg;
17205                    childRes.name = childPkg.packageName;
17206                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17207                    if (childPs != null) {
17208                        childRes.origUsers = childPs.queryInstalledUsers(
17209                                sUserManager.getUserIds(), true);
17210                    }
17211                    if ((mPackages.containsKey(childPkg.packageName))) {
17212                        childRes.removedInfo = new PackageRemovedInfo(this);
17213                        childRes.removedInfo.removedPackage = childPkg.packageName;
17214                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17215                    }
17216                    if (res.addedChildPackages == null) {
17217                        res.addedChildPackages = new ArrayMap<>();
17218                    }
17219                    res.addedChildPackages.put(childPkg.packageName, childRes);
17220                }
17221            }
17222        }
17223
17224        // If package doesn't declare API override, mark that we have an install
17225        // time CPU ABI override.
17226        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17227            pkg.cpuAbiOverride = args.abiOverride;
17228        }
17229
17230        String pkgName = res.name = pkg.packageName;
17231        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17232            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17233                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17234                return;
17235            }
17236        }
17237
17238        try {
17239            // either use what we've been given or parse directly from the APK
17240            if (args.certificates != null) {
17241                try {
17242                    PackageParser.populateCertificates(pkg, args.certificates);
17243                } catch (PackageParserException e) {
17244                    // there was something wrong with the certificates we were given;
17245                    // try to pull them from the APK
17246                    PackageParser.collectCertificates(pkg, parseFlags);
17247                }
17248            } else {
17249                PackageParser.collectCertificates(pkg, parseFlags);
17250            }
17251        } catch (PackageParserException e) {
17252            res.setError("Failed collect during installPackageLI", e);
17253            return;
17254        }
17255
17256        // Get rid of all references to package scan path via parser.
17257        pp = null;
17258        String oldCodePath = null;
17259        boolean systemApp = false;
17260        synchronized (mPackages) {
17261            // Check if installing already existing package
17262            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17263                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17264                if (pkg.mOriginalPackages != null
17265                        && pkg.mOriginalPackages.contains(oldName)
17266                        && mPackages.containsKey(oldName)) {
17267                    // This package is derived from an original package,
17268                    // and this device has been updating from that original
17269                    // name.  We must continue using the original name, so
17270                    // rename the new package here.
17271                    pkg.setPackageName(oldName);
17272                    pkgName = pkg.packageName;
17273                    replace = true;
17274                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17275                            + oldName + " pkgName=" + pkgName);
17276                } else if (mPackages.containsKey(pkgName)) {
17277                    // This package, under its official name, already exists
17278                    // on the device; we should replace it.
17279                    replace = true;
17280                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17281                }
17282
17283                // Child packages are installed through the parent package
17284                if (pkg.parentPackage != null) {
17285                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17286                            "Package " + pkg.packageName + " is child of package "
17287                                    + pkg.parentPackage.parentPackage + ". Child packages "
17288                                    + "can be updated only through the parent package.");
17289                    return;
17290                }
17291
17292                if (replace) {
17293                    // Prevent apps opting out from runtime permissions
17294                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17295                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17296                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17297                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17298                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17299                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17300                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17301                                        + " doesn't support runtime permissions but the old"
17302                                        + " target SDK " + oldTargetSdk + " does.");
17303                        return;
17304                    }
17305                    // Prevent apps from downgrading their targetSandbox.
17306                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17307                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17308                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17309                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17310                                "Package " + pkg.packageName + " new target sandbox "
17311                                + newTargetSandbox + " is incompatible with the previous value of"
17312                                + oldTargetSandbox + ".");
17313                        return;
17314                    }
17315
17316                    // Prevent installing of child packages
17317                    if (oldPackage.parentPackage != null) {
17318                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17319                                "Package " + pkg.packageName + " is child of package "
17320                                        + oldPackage.parentPackage + ". Child packages "
17321                                        + "can be updated only through the parent package.");
17322                        return;
17323                    }
17324                }
17325            }
17326
17327            PackageSetting ps = mSettings.mPackages.get(pkgName);
17328            if (ps != null) {
17329                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17330
17331                // Static shared libs have same package with different versions where
17332                // we internally use a synthetic package name to allow multiple versions
17333                // of the same package, therefore we need to compare signatures against
17334                // the package setting for the latest library version.
17335                PackageSetting signatureCheckPs = ps;
17336                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17337                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17338                    if (libraryEntry != null) {
17339                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17340                    }
17341                }
17342
17343                // Quick sanity check that we're signed correctly if updating;
17344                // we'll check this again later when scanning, but we want to
17345                // bail early here before tripping over redefined permissions.
17346                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
17347                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
17348                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17349                                + pkg.packageName + " upgrade keys do not match the "
17350                                + "previously installed version");
17351                        return;
17352                    }
17353                } else {
17354                    try {
17355                        verifySignaturesLP(signatureCheckPs, pkg);
17356                    } catch (PackageManagerException e) {
17357                        res.setError(e.error, e.getMessage());
17358                        return;
17359                    }
17360                }
17361
17362                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17363                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17364                    systemApp = (ps.pkg.applicationInfo.flags &
17365                            ApplicationInfo.FLAG_SYSTEM) != 0;
17366                }
17367                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17368            }
17369
17370            int N = pkg.permissions.size();
17371            for (int i = N-1; i >= 0; i--) {
17372                final PackageParser.Permission perm = pkg.permissions.get(i);
17373                final BasePermission bp =
17374                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
17375
17376                // Don't allow anyone but the system to define ephemeral permissions.
17377                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
17378                        && !systemApp) {
17379                    Slog.w(TAG, "Non-System package " + pkg.packageName
17380                            + " attempting to delcare ephemeral permission "
17381                            + perm.info.name + "; Removing ephemeral.");
17382                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
17383                }
17384
17385                // Check whether the newly-scanned package wants to define an already-defined perm
17386                if (bp != null) {
17387                    // If the defining package is signed with our cert, it's okay.  This
17388                    // also includes the "updating the same package" case, of course.
17389                    // "updating same package" could also involve key-rotation.
17390                    final boolean sigsOk;
17391                    final String sourcePackageName = bp.getSourcePackageName();
17392                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
17393                    if (sourcePackageName.equals(pkg.packageName)
17394                            && (shouldCheckUpgradeKeySetLP(sourcePackageSetting,
17395                                    scanFlags))) {
17396                        sigsOk = checkUpgradeKeySetLP(sourcePackageSetting, pkg);
17397                    } else {
17398                        sigsOk = compareSignatures(sourcePackageSetting.signatures.mSignatures,
17399                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
17400                    }
17401                    if (!sigsOk) {
17402                        // If the owning package is the system itself, we log but allow
17403                        // install to proceed; we fail the install on all other permission
17404                        // redefinitions.
17405                        if (!sourcePackageName.equals("android")) {
17406                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17407                                    + pkg.packageName + " attempting to redeclare permission "
17408                                    + perm.info.name + " already owned by " + sourcePackageName);
17409                            res.origPermission = perm.info.name;
17410                            res.origPackage = sourcePackageName;
17411                            return;
17412                        } else {
17413                            Slog.w(TAG, "Package " + pkg.packageName
17414                                    + " attempting to redeclare system permission "
17415                                    + perm.info.name + "; ignoring new declaration");
17416                            pkg.permissions.remove(i);
17417                        }
17418                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17419                        // Prevent apps to change protection level to dangerous from any other
17420                        // type as this would allow a privilege escalation where an app adds a
17421                        // normal/signature permission in other app's group and later redefines
17422                        // it as dangerous leading to the group auto-grant.
17423                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17424                                == PermissionInfo.PROTECTION_DANGEROUS) {
17425                            if (bp != null && !bp.isRuntime()) {
17426                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17427                                        + "non-runtime permission " + perm.info.name
17428                                        + " to runtime; keeping old protection level");
17429                                perm.info.protectionLevel = bp.getProtectionLevel();
17430                            }
17431                        }
17432                    }
17433                }
17434            }
17435        }
17436
17437        if (systemApp) {
17438            if (onExternal) {
17439                // Abort update; system app can't be replaced with app on sdcard
17440                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17441                        "Cannot install updates to system apps on sdcard");
17442                return;
17443            } else if (instantApp) {
17444                // Abort update; system app can't be replaced with an instant app
17445                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17446                        "Cannot update a system app with an instant app");
17447                return;
17448            }
17449        }
17450
17451        if (args.move != null) {
17452            // We did an in-place move, so dex is ready to roll
17453            scanFlags |= SCAN_NO_DEX;
17454            scanFlags |= SCAN_MOVE;
17455
17456            synchronized (mPackages) {
17457                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17458                if (ps == null) {
17459                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17460                            "Missing settings for moved package " + pkgName);
17461                }
17462
17463                // We moved the entire application as-is, so bring over the
17464                // previously derived ABI information.
17465                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17466                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17467            }
17468
17469        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17470            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17471            scanFlags |= SCAN_NO_DEX;
17472
17473            try {
17474                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17475                    args.abiOverride : pkg.cpuAbiOverride);
17476                final boolean extractNativeLibs = !pkg.isLibrary();
17477                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
17478                        extractNativeLibs, mAppLib32InstallDir);
17479            } catch (PackageManagerException pme) {
17480                Slog.e(TAG, "Error deriving application ABI", pme);
17481                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17482                return;
17483            }
17484
17485            // Shared libraries for the package need to be updated.
17486            synchronized (mPackages) {
17487                try {
17488                    updateSharedLibrariesLPr(pkg, null);
17489                } catch (PackageManagerException e) {
17490                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17491                }
17492            }
17493        }
17494
17495        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17496            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17497            return;
17498        }
17499
17500        // Verify if we need to dexopt the app.
17501        //
17502        // NOTE: it is *important* to call dexopt after doRename which will sync the
17503        // package data from PackageParser.Package and its corresponding ApplicationInfo.
17504        //
17505        // We only need to dexopt if the package meets ALL of the following conditions:
17506        //   1) it is not forward locked.
17507        //   2) it is not on on an external ASEC container.
17508        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17509        //
17510        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17511        // complete, so we skip this step during installation. Instead, we'll take extra time
17512        // the first time the instant app starts. It's preferred to do it this way to provide
17513        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17514        // middle of running an instant app. The default behaviour can be overridden
17515        // via gservices.
17516        final boolean performDexopt = !forwardLocked
17517            && !pkg.applicationInfo.isExternalAsec()
17518            && (!instantApp || Global.getInt(mContext.getContentResolver(),
17519                    Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
17520
17521        if (performDexopt) {
17522            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17523            // Do not run PackageDexOptimizer through the local performDexOpt
17524            // method because `pkg` may not be in `mPackages` yet.
17525            //
17526            // Also, don't fail application installs if the dexopt step fails.
17527            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17528                REASON_INSTALL,
17529                DexoptOptions.DEXOPT_BOOT_COMPLETE);
17530            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17531                null /* instructionSets */,
17532                getOrCreateCompilerPackageStats(pkg),
17533                mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17534                dexoptOptions);
17535            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17536        }
17537
17538        // Notify BackgroundDexOptService that the package has been changed.
17539        // If this is an update of a package which used to fail to compile,
17540        // BackgroundDexOptService will remove it from its blacklist.
17541        // TODO: Layering violation
17542        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17543
17544        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17545
17546        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17547                "installPackageLI")) {
17548            if (replace) {
17549                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17550                    // Static libs have a synthetic package name containing the version
17551                    // and cannot be updated as an update would get a new package name,
17552                    // unless this is the exact same version code which is useful for
17553                    // development.
17554                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17555                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
17556                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17557                                + "static-shared libs cannot be updated");
17558                        return;
17559                    }
17560                }
17561                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
17562                        installerPackageName, res, args.installReason);
17563            } else {
17564                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17565                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17566            }
17567        }
17568
17569        synchronized (mPackages) {
17570            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17571            if (ps != null) {
17572                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17573                ps.setUpdateAvailable(false /*updateAvailable*/);
17574            }
17575
17576            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17577            for (int i = 0; i < childCount; i++) {
17578                PackageParser.Package childPkg = pkg.childPackages.get(i);
17579                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17580                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17581                if (childPs != null) {
17582                    childRes.newUsers = childPs.queryInstalledUsers(
17583                            sUserManager.getUserIds(), true);
17584                }
17585            }
17586
17587            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17588                updateSequenceNumberLP(ps, res.newUsers);
17589                updateInstantAppInstallerLocked(pkgName);
17590            }
17591        }
17592    }
17593
17594    private void startIntentFilterVerifications(int userId, boolean replacing,
17595            PackageParser.Package pkg) {
17596        if (mIntentFilterVerifierComponent == null) {
17597            Slog.w(TAG, "No IntentFilter verification will not be done as "
17598                    + "there is no IntentFilterVerifier available!");
17599            return;
17600        }
17601
17602        final int verifierUid = getPackageUid(
17603                mIntentFilterVerifierComponent.getPackageName(),
17604                MATCH_DEBUG_TRIAGED_MISSING,
17605                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17606
17607        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17608        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17609        mHandler.sendMessage(msg);
17610
17611        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17612        for (int i = 0; i < childCount; i++) {
17613            PackageParser.Package childPkg = pkg.childPackages.get(i);
17614            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17615            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17616            mHandler.sendMessage(msg);
17617        }
17618    }
17619
17620    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17621            PackageParser.Package pkg) {
17622        int size = pkg.activities.size();
17623        if (size == 0) {
17624            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17625                    "No activity, so no need to verify any IntentFilter!");
17626            return;
17627        }
17628
17629        final boolean hasDomainURLs = hasDomainURLs(pkg);
17630        if (!hasDomainURLs) {
17631            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17632                    "No domain URLs, so no need to verify any IntentFilter!");
17633            return;
17634        }
17635
17636        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17637                + " if any IntentFilter from the " + size
17638                + " Activities needs verification ...");
17639
17640        int count = 0;
17641        final String packageName = pkg.packageName;
17642
17643        synchronized (mPackages) {
17644            // If this is a new install and we see that we've already run verification for this
17645            // package, we have nothing to do: it means the state was restored from backup.
17646            if (!replacing) {
17647                IntentFilterVerificationInfo ivi =
17648                        mSettings.getIntentFilterVerificationLPr(packageName);
17649                if (ivi != null) {
17650                    if (DEBUG_DOMAIN_VERIFICATION) {
17651                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17652                                + ivi.getStatusString());
17653                    }
17654                    return;
17655                }
17656            }
17657
17658            // If any filters need to be verified, then all need to be.
17659            boolean needToVerify = false;
17660            for (PackageParser.Activity a : pkg.activities) {
17661                for (ActivityIntentInfo filter : a.intents) {
17662                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17663                        if (DEBUG_DOMAIN_VERIFICATION) {
17664                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
17665                        }
17666                        needToVerify = true;
17667                        break;
17668                    }
17669                }
17670            }
17671
17672            if (needToVerify) {
17673                final int verificationId = mIntentFilterVerificationToken++;
17674                for (PackageParser.Activity a : pkg.activities) {
17675                    for (ActivityIntentInfo filter : a.intents) {
17676                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17677                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17678                                    "Verification needed for IntentFilter:" + filter.toString());
17679                            mIntentFilterVerifier.addOneIntentFilterVerification(
17680                                    verifierUid, userId, verificationId, filter, packageName);
17681                            count++;
17682                        }
17683                    }
17684                }
17685            }
17686        }
17687
17688        if (count > 0) {
17689            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17690                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17691                    +  " for userId:" + userId);
17692            mIntentFilterVerifier.startVerifications(userId);
17693        } else {
17694            if (DEBUG_DOMAIN_VERIFICATION) {
17695                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17696            }
17697        }
17698    }
17699
17700    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17701        final ComponentName cn  = filter.activity.getComponentName();
17702        final String packageName = cn.getPackageName();
17703
17704        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17705                packageName);
17706        if (ivi == null) {
17707            return true;
17708        }
17709        int status = ivi.getStatus();
17710        switch (status) {
17711            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17712            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17713                return true;
17714
17715            default:
17716                // Nothing to do
17717                return false;
17718        }
17719    }
17720
17721    private static boolean isMultiArch(ApplicationInfo info) {
17722        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17723    }
17724
17725    private static boolean isExternal(PackageParser.Package pkg) {
17726        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17727    }
17728
17729    private static boolean isExternal(PackageSetting ps) {
17730        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17731    }
17732
17733    private static boolean isSystemApp(PackageParser.Package pkg) {
17734        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17735    }
17736
17737    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17738        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17739    }
17740
17741    private static boolean isOemApp(PackageParser.Package pkg) {
17742        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17743    }
17744
17745    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17746        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17747    }
17748
17749    private static boolean isSystemApp(PackageSetting ps) {
17750        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17751    }
17752
17753    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17754        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17755    }
17756
17757    private int packageFlagsToInstallFlags(PackageSetting ps) {
17758        int installFlags = 0;
17759        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17760            // This existing package was an external ASEC install when we have
17761            // the external flag without a UUID
17762            installFlags |= PackageManager.INSTALL_EXTERNAL;
17763        }
17764        if (ps.isForwardLocked()) {
17765            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17766        }
17767        return installFlags;
17768    }
17769
17770    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17771        if (isExternal(pkg)) {
17772            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17773                return StorageManager.UUID_PRIMARY_PHYSICAL;
17774            } else {
17775                return pkg.volumeUuid;
17776            }
17777        } else {
17778            return StorageManager.UUID_PRIVATE_INTERNAL;
17779        }
17780    }
17781
17782    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17783        if (isExternal(pkg)) {
17784            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17785                return mSettings.getExternalVersion();
17786            } else {
17787                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17788            }
17789        } else {
17790            return mSettings.getInternalVersion();
17791        }
17792    }
17793
17794    private void deleteTempPackageFiles() {
17795        final FilenameFilter filter = new FilenameFilter() {
17796            public boolean accept(File dir, String name) {
17797                return name.startsWith("vmdl") && name.endsWith(".tmp");
17798            }
17799        };
17800        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17801            file.delete();
17802        }
17803    }
17804
17805    @Override
17806    public void deletePackageAsUser(String packageName, int versionCode,
17807            IPackageDeleteObserver observer, int userId, int flags) {
17808        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17809                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17810    }
17811
17812    @Override
17813    public void deletePackageVersioned(VersionedPackage versionedPackage,
17814            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17815        final int callingUid = Binder.getCallingUid();
17816        mContext.enforceCallingOrSelfPermission(
17817                android.Manifest.permission.DELETE_PACKAGES, null);
17818        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17819        Preconditions.checkNotNull(versionedPackage);
17820        Preconditions.checkNotNull(observer);
17821        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17822                PackageManager.VERSION_CODE_HIGHEST,
17823                Integer.MAX_VALUE, "versionCode must be >= -1");
17824
17825        final String packageName = versionedPackage.getPackageName();
17826        final int versionCode = versionedPackage.getVersionCode();
17827        final String internalPackageName;
17828        synchronized (mPackages) {
17829            // Normalize package name to handle renamed packages and static libs
17830            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17831                    versionedPackage.getVersionCode());
17832        }
17833
17834        final int uid = Binder.getCallingUid();
17835        if (!isOrphaned(internalPackageName)
17836                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17837            try {
17838                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17839                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17840                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17841                observer.onUserActionRequired(intent);
17842            } catch (RemoteException re) {
17843            }
17844            return;
17845        }
17846        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17847        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17848        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17849            mContext.enforceCallingOrSelfPermission(
17850                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17851                    "deletePackage for user " + userId);
17852        }
17853
17854        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17855            try {
17856                observer.onPackageDeleted(packageName,
17857                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17858            } catch (RemoteException re) {
17859            }
17860            return;
17861        }
17862
17863        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17864            try {
17865                observer.onPackageDeleted(packageName,
17866                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17867            } catch (RemoteException re) {
17868            }
17869            return;
17870        }
17871
17872        if (DEBUG_REMOVE) {
17873            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17874                    + " deleteAllUsers: " + deleteAllUsers + " version="
17875                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17876                    ? "VERSION_CODE_HIGHEST" : versionCode));
17877        }
17878        // Queue up an async operation since the package deletion may take a little while.
17879        mHandler.post(new Runnable() {
17880            public void run() {
17881                mHandler.removeCallbacks(this);
17882                int returnCode;
17883                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17884                boolean doDeletePackage = true;
17885                if (ps != null) {
17886                    final boolean targetIsInstantApp =
17887                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17888                    doDeletePackage = !targetIsInstantApp
17889                            || canViewInstantApps;
17890                }
17891                if (doDeletePackage) {
17892                    if (!deleteAllUsers) {
17893                        returnCode = deletePackageX(internalPackageName, versionCode,
17894                                userId, deleteFlags);
17895                    } else {
17896                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17897                                internalPackageName, users);
17898                        // If nobody is blocking uninstall, proceed with delete for all users
17899                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17900                            returnCode = deletePackageX(internalPackageName, versionCode,
17901                                    userId, deleteFlags);
17902                        } else {
17903                            // Otherwise uninstall individually for users with blockUninstalls=false
17904                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17905                            for (int userId : users) {
17906                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17907                                    returnCode = deletePackageX(internalPackageName, versionCode,
17908                                            userId, userFlags);
17909                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17910                                        Slog.w(TAG, "Package delete failed for user " + userId
17911                                                + ", returnCode " + returnCode);
17912                                    }
17913                                }
17914                            }
17915                            // The app has only been marked uninstalled for certain users.
17916                            // We still need to report that delete was blocked
17917                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17918                        }
17919                    }
17920                } else {
17921                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17922                }
17923                try {
17924                    observer.onPackageDeleted(packageName, returnCode, null);
17925                } catch (RemoteException e) {
17926                    Log.i(TAG, "Observer no longer exists.");
17927                } //end catch
17928            } //end run
17929        });
17930    }
17931
17932    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17933        if (pkg.staticSharedLibName != null) {
17934            return pkg.manifestPackageName;
17935        }
17936        return pkg.packageName;
17937    }
17938
17939    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17940        // Handle renamed packages
17941        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17942        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17943
17944        // Is this a static library?
17945        SparseArray<SharedLibraryEntry> versionedLib =
17946                mStaticLibsByDeclaringPackage.get(packageName);
17947        if (versionedLib == null || versionedLib.size() <= 0) {
17948            return packageName;
17949        }
17950
17951        // Figure out which lib versions the caller can see
17952        SparseIntArray versionsCallerCanSee = null;
17953        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17954        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17955                && callingAppId != Process.ROOT_UID) {
17956            versionsCallerCanSee = new SparseIntArray();
17957            String libName = versionedLib.valueAt(0).info.getName();
17958            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17959            if (uidPackages != null) {
17960                for (String uidPackage : uidPackages) {
17961                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17962                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17963                    if (libIdx >= 0) {
17964                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17965                        versionsCallerCanSee.append(libVersion, libVersion);
17966                    }
17967                }
17968            }
17969        }
17970
17971        // Caller can see nothing - done
17972        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17973            return packageName;
17974        }
17975
17976        // Find the version the caller can see and the app version code
17977        SharedLibraryEntry highestVersion = null;
17978        final int versionCount = versionedLib.size();
17979        for (int i = 0; i < versionCount; i++) {
17980            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17981            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17982                    libEntry.info.getVersion()) < 0) {
17983                continue;
17984            }
17985            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
17986            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17987                if (libVersionCode == versionCode) {
17988                    return libEntry.apk;
17989                }
17990            } else if (highestVersion == null) {
17991                highestVersion = libEntry;
17992            } else if (libVersionCode  > highestVersion.info
17993                    .getDeclaringPackage().getVersionCode()) {
17994                highestVersion = libEntry;
17995            }
17996        }
17997
17998        if (highestVersion != null) {
17999            return highestVersion.apk;
18000        }
18001
18002        return packageName;
18003    }
18004
18005    boolean isCallerVerifier(int callingUid) {
18006        final int callingUserId = UserHandle.getUserId(callingUid);
18007        return mRequiredVerifierPackage != null &&
18008                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
18009    }
18010
18011    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18012        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18013              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18014            return true;
18015        }
18016        final int callingUserId = UserHandle.getUserId(callingUid);
18017        // If the caller installed the pkgName, then allow it to silently uninstall.
18018        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18019            return true;
18020        }
18021
18022        // Allow package verifier to silently uninstall.
18023        if (mRequiredVerifierPackage != null &&
18024                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18025            return true;
18026        }
18027
18028        // Allow package uninstaller to silently uninstall.
18029        if (mRequiredUninstallerPackage != null &&
18030                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18031            return true;
18032        }
18033
18034        // Allow storage manager to silently uninstall.
18035        if (mStorageManagerPackage != null &&
18036                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18037            return true;
18038        }
18039
18040        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
18041        // uninstall for device owner provisioning.
18042        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
18043                == PERMISSION_GRANTED) {
18044            return true;
18045        }
18046
18047        return false;
18048    }
18049
18050    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18051        int[] result = EMPTY_INT_ARRAY;
18052        for (int userId : userIds) {
18053            if (getBlockUninstallForUser(packageName, userId)) {
18054                result = ArrayUtils.appendInt(result, userId);
18055            }
18056        }
18057        return result;
18058    }
18059
18060    @Override
18061    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18062        final int callingUid = Binder.getCallingUid();
18063        if (getInstantAppPackageName(callingUid) != null
18064                && !isCallerSameApp(packageName, callingUid)) {
18065            return false;
18066        }
18067        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18068    }
18069
18070    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18071        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18072                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18073        try {
18074            if (dpm != null) {
18075                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18076                        /* callingUserOnly =*/ false);
18077                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18078                        : deviceOwnerComponentName.getPackageName();
18079                // Does the package contains the device owner?
18080                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18081                // this check is probably not needed, since DO should be registered as a device
18082                // admin on some user too. (Original bug for this: b/17657954)
18083                if (packageName.equals(deviceOwnerPackageName)) {
18084                    return true;
18085                }
18086                // Does it contain a device admin for any user?
18087                int[] users;
18088                if (userId == UserHandle.USER_ALL) {
18089                    users = sUserManager.getUserIds();
18090                } else {
18091                    users = new int[]{userId};
18092                }
18093                for (int i = 0; i < users.length; ++i) {
18094                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18095                        return true;
18096                    }
18097                }
18098            }
18099        } catch (RemoteException e) {
18100        }
18101        return false;
18102    }
18103
18104    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18105        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18106    }
18107
18108    /**
18109     *  This method is an internal method that could be get invoked either
18110     *  to delete an installed package or to clean up a failed installation.
18111     *  After deleting an installed package, a broadcast is sent to notify any
18112     *  listeners that the package has been removed. For cleaning up a failed
18113     *  installation, the broadcast is not necessary since the package's
18114     *  installation wouldn't have sent the initial broadcast either
18115     *  The key steps in deleting a package are
18116     *  deleting the package information in internal structures like mPackages,
18117     *  deleting the packages base directories through installd
18118     *  updating mSettings to reflect current status
18119     *  persisting settings for later use
18120     *  sending a broadcast if necessary
18121     */
18122    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18123        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18124        final boolean res;
18125
18126        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18127                ? UserHandle.USER_ALL : userId;
18128
18129        if (isPackageDeviceAdmin(packageName, removeUser)) {
18130            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18131            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18132        }
18133
18134        PackageSetting uninstalledPs = null;
18135        PackageParser.Package pkg = null;
18136
18137        // for the uninstall-updates case and restricted profiles, remember the per-
18138        // user handle installed state
18139        int[] allUsers;
18140        synchronized (mPackages) {
18141            uninstalledPs = mSettings.mPackages.get(packageName);
18142            if (uninstalledPs == null) {
18143                Slog.w(TAG, "Not removing non-existent package " + packageName);
18144                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18145            }
18146
18147            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18148                    && uninstalledPs.versionCode != versionCode) {
18149                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18150                        + uninstalledPs.versionCode + " != " + versionCode);
18151                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18152            }
18153
18154            // Static shared libs can be declared by any package, so let us not
18155            // allow removing a package if it provides a lib others depend on.
18156            pkg = mPackages.get(packageName);
18157
18158            allUsers = sUserManager.getUserIds();
18159
18160            if (pkg != null && pkg.staticSharedLibName != null) {
18161                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18162                        pkg.staticSharedLibVersion);
18163                if (libEntry != null) {
18164                    for (int currUserId : allUsers) {
18165                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18166                            continue;
18167                        }
18168                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18169                                libEntry.info, 0, currUserId);
18170                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18171                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18172                                    + " hosting lib " + libEntry.info.getName() + " version "
18173                                    + libEntry.info.getVersion() + " used by " + libClientPackages
18174                                    + " for user " + currUserId);
18175                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18176                        }
18177                    }
18178                }
18179            }
18180
18181            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18182        }
18183
18184        final int freezeUser;
18185        if (isUpdatedSystemApp(uninstalledPs)
18186                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18187            // We're downgrading a system app, which will apply to all users, so
18188            // freeze them all during the downgrade
18189            freezeUser = UserHandle.USER_ALL;
18190        } else {
18191            freezeUser = removeUser;
18192        }
18193
18194        synchronized (mInstallLock) {
18195            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18196            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18197                    deleteFlags, "deletePackageX")) {
18198                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18199                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18200            }
18201            synchronized (mPackages) {
18202                if (res) {
18203                    if (pkg != null) {
18204                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18205                    }
18206                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18207                    updateInstantAppInstallerLocked(packageName);
18208                }
18209            }
18210        }
18211
18212        if (res) {
18213            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18214            info.sendPackageRemovedBroadcasts(killApp);
18215            info.sendSystemPackageUpdatedBroadcasts();
18216            info.sendSystemPackageAppearedBroadcasts();
18217        }
18218        // Force a gc here.
18219        Runtime.getRuntime().gc();
18220        // Delete the resources here after sending the broadcast to let
18221        // other processes clean up before deleting resources.
18222        if (info.args != null) {
18223            synchronized (mInstallLock) {
18224                info.args.doPostDeleteLI(true);
18225            }
18226        }
18227
18228        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18229    }
18230
18231    static class PackageRemovedInfo {
18232        final PackageSender packageSender;
18233        String removedPackage;
18234        String installerPackageName;
18235        int uid = -1;
18236        int removedAppId = -1;
18237        int[] origUsers;
18238        int[] removedUsers = null;
18239        int[] broadcastUsers = null;
18240        SparseArray<Integer> installReasons;
18241        boolean isRemovedPackageSystemUpdate = false;
18242        boolean isUpdate;
18243        boolean dataRemoved;
18244        boolean removedForAllUsers;
18245        boolean isStaticSharedLib;
18246        // Clean up resources deleted packages.
18247        InstallArgs args = null;
18248        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18249        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18250
18251        PackageRemovedInfo(PackageSender packageSender) {
18252            this.packageSender = packageSender;
18253        }
18254
18255        void sendPackageRemovedBroadcasts(boolean killApp) {
18256            sendPackageRemovedBroadcastInternal(killApp);
18257            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18258            for (int i = 0; i < childCount; i++) {
18259                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18260                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18261            }
18262        }
18263
18264        void sendSystemPackageUpdatedBroadcasts() {
18265            if (isRemovedPackageSystemUpdate) {
18266                sendSystemPackageUpdatedBroadcastsInternal();
18267                final int childCount = (removedChildPackages != null)
18268                        ? removedChildPackages.size() : 0;
18269                for (int i = 0; i < childCount; i++) {
18270                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18271                    if (childInfo.isRemovedPackageSystemUpdate) {
18272                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18273                    }
18274                }
18275            }
18276        }
18277
18278        void sendSystemPackageAppearedBroadcasts() {
18279            final int packageCount = (appearedChildPackages != null)
18280                    ? appearedChildPackages.size() : 0;
18281            for (int i = 0; i < packageCount; i++) {
18282                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18283                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18284                    true /*sendBootCompleted*/, false /*startReceiver*/,
18285                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
18286            }
18287        }
18288
18289        private void sendSystemPackageUpdatedBroadcastsInternal() {
18290            Bundle extras = new Bundle(2);
18291            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18292            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18293            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18294                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18295            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18296                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18297            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18298                null, null, 0, removedPackage, null, null);
18299            if (installerPackageName != null) {
18300                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18301                        removedPackage, extras, 0 /*flags*/,
18302                        installerPackageName, null, null);
18303                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18304                        removedPackage, extras, 0 /*flags*/,
18305                        installerPackageName, null, null);
18306            }
18307        }
18308
18309        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18310            // Don't send static shared library removal broadcasts as these
18311            // libs are visible only the the apps that depend on them an one
18312            // cannot remove the library if it has a dependency.
18313            if (isStaticSharedLib) {
18314                return;
18315            }
18316            Bundle extras = new Bundle(2);
18317            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18318            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18319            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18320            if (isUpdate || isRemovedPackageSystemUpdate) {
18321                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18322            }
18323            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18324            if (removedPackage != null) {
18325                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18326                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
18327                if (installerPackageName != null) {
18328                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18329                            removedPackage, extras, 0 /*flags*/,
18330                            installerPackageName, null, broadcastUsers);
18331                }
18332                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18333                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18334                        removedPackage, extras,
18335                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18336                        null, null, broadcastUsers);
18337                }
18338            }
18339            if (removedAppId >= 0) {
18340                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18341                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18342                    null, null, broadcastUsers);
18343            }
18344        }
18345
18346        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18347            removedUsers = userIds;
18348            if (removedUsers == null) {
18349                broadcastUsers = null;
18350                return;
18351            }
18352
18353            broadcastUsers = EMPTY_INT_ARRAY;
18354            for (int i = userIds.length - 1; i >= 0; --i) {
18355                final int userId = userIds[i];
18356                if (deletedPackageSetting.getInstantApp(userId)) {
18357                    continue;
18358                }
18359                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18360            }
18361        }
18362    }
18363
18364    /*
18365     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18366     * flag is not set, the data directory is removed as well.
18367     * make sure this flag is set for partially installed apps. If not its meaningless to
18368     * delete a partially installed application.
18369     */
18370    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18371            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18372        String packageName = ps.name;
18373        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18374        // Retrieve object to delete permissions for shared user later on
18375        final PackageParser.Package deletedPkg;
18376        final PackageSetting deletedPs;
18377        // reader
18378        synchronized (mPackages) {
18379            deletedPkg = mPackages.get(packageName);
18380            deletedPs = mSettings.mPackages.get(packageName);
18381            if (outInfo != null) {
18382                outInfo.removedPackage = packageName;
18383                outInfo.installerPackageName = ps.installerPackageName;
18384                outInfo.isStaticSharedLib = deletedPkg != null
18385                        && deletedPkg.staticSharedLibName != null;
18386                outInfo.populateUsers(deletedPs == null ? null
18387                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18388            }
18389        }
18390
18391        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
18392
18393        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18394            final PackageParser.Package resolvedPkg;
18395            if (deletedPkg != null) {
18396                resolvedPkg = deletedPkg;
18397            } else {
18398                // We don't have a parsed package when it lives on an ejected
18399                // adopted storage device, so fake something together
18400                resolvedPkg = new PackageParser.Package(ps.name);
18401                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18402            }
18403            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18404                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18405            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18406            if (outInfo != null) {
18407                outInfo.dataRemoved = true;
18408            }
18409            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18410        }
18411
18412        int removedAppId = -1;
18413
18414        // writer
18415        synchronized (mPackages) {
18416            boolean installedStateChanged = false;
18417            if (deletedPs != null) {
18418                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18419                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18420                    clearDefaultBrowserIfNeeded(packageName);
18421                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18422                    removedAppId = mSettings.removePackageLPw(packageName);
18423                    if (outInfo != null) {
18424                        outInfo.removedAppId = removedAppId;
18425                    }
18426                    updatePermissionsLPw(deletedPs.name, null, 0);
18427                    if (deletedPs.sharedUser != null) {
18428                        // Remove permissions associated with package. Since runtime
18429                        // permissions are per user we have to kill the removed package
18430                        // or packages running under the shared user of the removed
18431                        // package if revoking the permissions requested only by the removed
18432                        // package is successful and this causes a change in gids.
18433                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18434                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18435                                    userId);
18436                            if (userIdToKill == UserHandle.USER_ALL
18437                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18438                                // If gids changed for this user, kill all affected packages.
18439                                mHandler.post(new Runnable() {
18440                                    @Override
18441                                    public void run() {
18442                                        // This has to happen with no lock held.
18443                                        killApplication(deletedPs.name, deletedPs.appId,
18444                                                KILL_APP_REASON_GIDS_CHANGED);
18445                                    }
18446                                });
18447                                break;
18448                            }
18449                        }
18450                    }
18451                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18452                }
18453                // make sure to preserve per-user disabled state if this removal was just
18454                // a downgrade of a system app to the factory package
18455                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18456                    if (DEBUG_REMOVE) {
18457                        Slog.d(TAG, "Propagating install state across downgrade");
18458                    }
18459                    for (int userId : allUserHandles) {
18460                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18461                        if (DEBUG_REMOVE) {
18462                            Slog.d(TAG, "    user " + userId + " => " + installed);
18463                        }
18464                        if (installed != ps.getInstalled(userId)) {
18465                            installedStateChanged = true;
18466                        }
18467                        ps.setInstalled(installed, userId);
18468                    }
18469                }
18470            }
18471            // can downgrade to reader
18472            if (writeSettings) {
18473                // Save settings now
18474                mSettings.writeLPr();
18475            }
18476            if (installedStateChanged) {
18477                mSettings.writeKernelMappingLPr(ps);
18478            }
18479        }
18480        if (removedAppId != -1) {
18481            // A user ID was deleted here. Go through all users and remove it
18482            // from KeyStore.
18483            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18484        }
18485    }
18486
18487    static boolean locationIsPrivileged(File path) {
18488        try {
18489            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
18490                    .getCanonicalPath();
18491            return path.getCanonicalPath().startsWith(privilegedAppDir);
18492        } catch (IOException e) {
18493            Slog.e(TAG, "Unable to access code path " + path);
18494        }
18495        return false;
18496    }
18497
18498    static boolean locationIsOem(File path) {
18499        try {
18500            return path.getCanonicalPath().startsWith(
18501                    Environment.getOemDirectory().getCanonicalPath());
18502        } catch (IOException e) {
18503            Slog.e(TAG, "Unable to access code path " + path);
18504        }
18505        return false;
18506    }
18507
18508    /*
18509     * Tries to delete system package.
18510     */
18511    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18512            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18513            boolean writeSettings) {
18514        if (deletedPs.parentPackageName != null) {
18515            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18516            return false;
18517        }
18518
18519        final boolean applyUserRestrictions
18520                = (allUserHandles != null) && (outInfo.origUsers != null);
18521        final PackageSetting disabledPs;
18522        // Confirm if the system package has been updated
18523        // An updated system app can be deleted. This will also have to restore
18524        // the system pkg from system partition
18525        // reader
18526        synchronized (mPackages) {
18527            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18528        }
18529
18530        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18531                + " disabledPs=" + disabledPs);
18532
18533        if (disabledPs == null) {
18534            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18535            return false;
18536        } else if (DEBUG_REMOVE) {
18537            Slog.d(TAG, "Deleting system pkg from data partition");
18538        }
18539
18540        if (DEBUG_REMOVE) {
18541            if (applyUserRestrictions) {
18542                Slog.d(TAG, "Remembering install states:");
18543                for (int userId : allUserHandles) {
18544                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18545                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18546                }
18547            }
18548        }
18549
18550        // Delete the updated package
18551        outInfo.isRemovedPackageSystemUpdate = true;
18552        if (outInfo.removedChildPackages != null) {
18553            final int childCount = (deletedPs.childPackageNames != null)
18554                    ? deletedPs.childPackageNames.size() : 0;
18555            for (int i = 0; i < childCount; i++) {
18556                String childPackageName = deletedPs.childPackageNames.get(i);
18557                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18558                        .contains(childPackageName)) {
18559                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18560                            childPackageName);
18561                    if (childInfo != null) {
18562                        childInfo.isRemovedPackageSystemUpdate = true;
18563                    }
18564                }
18565            }
18566        }
18567
18568        if (disabledPs.versionCode < deletedPs.versionCode) {
18569            // Delete data for downgrades
18570            flags &= ~PackageManager.DELETE_KEEP_DATA;
18571        } else {
18572            // Preserve data by setting flag
18573            flags |= PackageManager.DELETE_KEEP_DATA;
18574        }
18575
18576        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18577                outInfo, writeSettings, disabledPs.pkg);
18578        if (!ret) {
18579            return false;
18580        }
18581
18582        // writer
18583        synchronized (mPackages) {
18584            // NOTE: The system package always needs to be enabled; even if it's for
18585            // a compressed stub. If we don't, installing the system package fails
18586            // during scan [scanning checks the disabled packages]. We will reverse
18587            // this later, after we've "installed" the stub.
18588            // Reinstate the old system package
18589            enableSystemPackageLPw(disabledPs.pkg);
18590            // Remove any native libraries from the upgraded package.
18591            removeNativeBinariesLI(deletedPs);
18592        }
18593
18594        // Install the system package
18595        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18596        try {
18597            installPackageFromSystemLIF(disabledPs.codePath, false /*isPrivileged*/, allUserHandles,
18598                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18599        } catch (PackageManagerException e) {
18600            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18601                    + e.getMessage());
18602            return false;
18603        } finally {
18604            if (disabledPs.pkg.isStub) {
18605                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18606            }
18607        }
18608        return true;
18609    }
18610
18611    /**
18612     * Installs a package that's already on the system partition.
18613     */
18614    private PackageParser.Package installPackageFromSystemLIF(@NonNull File codePath,
18615            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18616            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18617                    throws PackageManagerException {
18618        int parseFlags = mDefParseFlags
18619                | PackageParser.PARSE_MUST_BE_APK
18620                | PackageParser.PARSE_IS_SYSTEM
18621                | PackageParser.PARSE_IS_SYSTEM_DIR;
18622        if (isPrivileged || locationIsPrivileged(codePath)) {
18623            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
18624        }
18625        if (locationIsOem(codePath)) {
18626            parseFlags |= PackageParser.PARSE_IS_OEM;
18627        }
18628
18629        final PackageParser.Package newPkg =
18630                scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 0 /*currentTime*/, null);
18631
18632        try {
18633            // update shared libraries for the newly re-installed system package
18634            updateSharedLibrariesLPr(newPkg, null);
18635        } catch (PackageManagerException e) {
18636            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18637        }
18638
18639        prepareAppDataAfterInstallLIF(newPkg);
18640
18641        // writer
18642        synchronized (mPackages) {
18643            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
18644
18645            // Propagate the permissions state as we do not want to drop on the floor
18646            // runtime permissions. The update permissions method below will take
18647            // care of removing obsolete permissions and grant install permissions.
18648            if (origPermissionState != null) {
18649                ps.getPermissionsState().copyFrom(origPermissionState);
18650            }
18651            updatePermissionsLPw(newPkg.packageName, newPkg,
18652                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
18653
18654            final boolean applyUserRestrictions
18655                    = (allUserHandles != null) && (origUserHandles != null);
18656            if (applyUserRestrictions) {
18657                boolean installedStateChanged = false;
18658                if (DEBUG_REMOVE) {
18659                    Slog.d(TAG, "Propagating install state across reinstall");
18660                }
18661                for (int userId : allUserHandles) {
18662                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18663                    if (DEBUG_REMOVE) {
18664                        Slog.d(TAG, "    user " + userId + " => " + installed);
18665                    }
18666                    if (installed != ps.getInstalled(userId)) {
18667                        installedStateChanged = true;
18668                    }
18669                    ps.setInstalled(installed, userId);
18670
18671                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18672                }
18673                // Regardless of writeSettings we need to ensure that this restriction
18674                // state propagation is persisted
18675                mSettings.writeAllUsersPackageRestrictionsLPr();
18676                if (installedStateChanged) {
18677                    mSettings.writeKernelMappingLPr(ps);
18678                }
18679            }
18680            // can downgrade to reader here
18681            if (writeSettings) {
18682                mSettings.writeLPr();
18683            }
18684        }
18685        return newPkg;
18686    }
18687
18688    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18689            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18690            PackageRemovedInfo outInfo, boolean writeSettings,
18691            PackageParser.Package replacingPackage) {
18692        synchronized (mPackages) {
18693            if (outInfo != null) {
18694                outInfo.uid = ps.appId;
18695            }
18696
18697            if (outInfo != null && outInfo.removedChildPackages != null) {
18698                final int childCount = (ps.childPackageNames != null)
18699                        ? ps.childPackageNames.size() : 0;
18700                for (int i = 0; i < childCount; i++) {
18701                    String childPackageName = ps.childPackageNames.get(i);
18702                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18703                    if (childPs == null) {
18704                        return false;
18705                    }
18706                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18707                            childPackageName);
18708                    if (childInfo != null) {
18709                        childInfo.uid = childPs.appId;
18710                    }
18711                }
18712            }
18713        }
18714
18715        // Delete package data from internal structures and also remove data if flag is set
18716        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18717
18718        // Delete the child packages data
18719        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18720        for (int i = 0; i < childCount; i++) {
18721            PackageSetting childPs;
18722            synchronized (mPackages) {
18723                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18724            }
18725            if (childPs != null) {
18726                PackageRemovedInfo childOutInfo = (outInfo != null
18727                        && outInfo.removedChildPackages != null)
18728                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18729                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18730                        && (replacingPackage != null
18731                        && !replacingPackage.hasChildPackage(childPs.name))
18732                        ? flags & ~DELETE_KEEP_DATA : flags;
18733                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18734                        deleteFlags, writeSettings);
18735            }
18736        }
18737
18738        // Delete application code and resources only for parent packages
18739        if (ps.parentPackageName == null) {
18740            if (deleteCodeAndResources && (outInfo != null)) {
18741                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18742                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18743                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18744            }
18745        }
18746
18747        return true;
18748    }
18749
18750    @Override
18751    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18752            int userId) {
18753        mContext.enforceCallingOrSelfPermission(
18754                android.Manifest.permission.DELETE_PACKAGES, null);
18755        synchronized (mPackages) {
18756            // Cannot block uninstall of static shared libs as they are
18757            // considered a part of the using app (emulating static linking).
18758            // Also static libs are installed always on internal storage.
18759            PackageParser.Package pkg = mPackages.get(packageName);
18760            if (pkg != null && pkg.staticSharedLibName != null) {
18761                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18762                        + " providing static shared library: " + pkg.staticSharedLibName);
18763                return false;
18764            }
18765            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18766            mSettings.writePackageRestrictionsLPr(userId);
18767        }
18768        return true;
18769    }
18770
18771    @Override
18772    public boolean getBlockUninstallForUser(String packageName, int userId) {
18773        synchronized (mPackages) {
18774            final PackageSetting ps = mSettings.mPackages.get(packageName);
18775            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18776                return false;
18777            }
18778            return mSettings.getBlockUninstallLPr(userId, packageName);
18779        }
18780    }
18781
18782    @Override
18783    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18784        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18785        synchronized (mPackages) {
18786            PackageSetting ps = mSettings.mPackages.get(packageName);
18787            if (ps == null) {
18788                Log.w(TAG, "Package doesn't exist: " + packageName);
18789                return false;
18790            }
18791            if (systemUserApp) {
18792                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18793            } else {
18794                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18795            }
18796            mSettings.writeLPr();
18797        }
18798        return true;
18799    }
18800
18801    /*
18802     * This method handles package deletion in general
18803     */
18804    private boolean deletePackageLIF(String packageName, UserHandle user,
18805            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18806            PackageRemovedInfo outInfo, boolean writeSettings,
18807            PackageParser.Package replacingPackage) {
18808        if (packageName == null) {
18809            Slog.w(TAG, "Attempt to delete null packageName.");
18810            return false;
18811        }
18812
18813        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18814
18815        PackageSetting ps;
18816        synchronized (mPackages) {
18817            ps = mSettings.mPackages.get(packageName);
18818            if (ps == null) {
18819                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18820                return false;
18821            }
18822
18823            if (ps.parentPackageName != null && (!isSystemApp(ps)
18824                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18825                if (DEBUG_REMOVE) {
18826                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18827                            + ((user == null) ? UserHandle.USER_ALL : user));
18828                }
18829                final int removedUserId = (user != null) ? user.getIdentifier()
18830                        : UserHandle.USER_ALL;
18831                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18832                    return false;
18833                }
18834                markPackageUninstalledForUserLPw(ps, user);
18835                scheduleWritePackageRestrictionsLocked(user);
18836                return true;
18837            }
18838        }
18839
18840        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18841                && user.getIdentifier() != UserHandle.USER_ALL)) {
18842            // The caller is asking that the package only be deleted for a single
18843            // user.  To do this, we just mark its uninstalled state and delete
18844            // its data. If this is a system app, we only allow this to happen if
18845            // they have set the special DELETE_SYSTEM_APP which requests different
18846            // semantics than normal for uninstalling system apps.
18847            markPackageUninstalledForUserLPw(ps, user);
18848
18849            if (!isSystemApp(ps)) {
18850                // Do not uninstall the APK if an app should be cached
18851                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18852                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18853                    // Other user still have this package installed, so all
18854                    // we need to do is clear this user's data and save that
18855                    // it is uninstalled.
18856                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18857                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18858                        return false;
18859                    }
18860                    scheduleWritePackageRestrictionsLocked(user);
18861                    return true;
18862                } else {
18863                    // We need to set it back to 'installed' so the uninstall
18864                    // broadcasts will be sent correctly.
18865                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18866                    ps.setInstalled(true, user.getIdentifier());
18867                    mSettings.writeKernelMappingLPr(ps);
18868                }
18869            } else {
18870                // This is a system app, so we assume that the
18871                // other users still have this package installed, so all
18872                // we need to do is clear this user's data and save that
18873                // it is uninstalled.
18874                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18875                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18876                    return false;
18877                }
18878                scheduleWritePackageRestrictionsLocked(user);
18879                return true;
18880            }
18881        }
18882
18883        // If we are deleting a composite package for all users, keep track
18884        // of result for each child.
18885        if (ps.childPackageNames != null && outInfo != null) {
18886            synchronized (mPackages) {
18887                final int childCount = ps.childPackageNames.size();
18888                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18889                for (int i = 0; i < childCount; i++) {
18890                    String childPackageName = ps.childPackageNames.get(i);
18891                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18892                    childInfo.removedPackage = childPackageName;
18893                    childInfo.installerPackageName = ps.installerPackageName;
18894                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18895                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18896                    if (childPs != null) {
18897                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18898                    }
18899                }
18900            }
18901        }
18902
18903        boolean ret = false;
18904        if (isSystemApp(ps)) {
18905            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18906            // When an updated system application is deleted we delete the existing resources
18907            // as well and fall back to existing code in system partition
18908            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18909        } else {
18910            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18911            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18912                    outInfo, writeSettings, replacingPackage);
18913        }
18914
18915        // Take a note whether we deleted the package for all users
18916        if (outInfo != null) {
18917            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18918            if (outInfo.removedChildPackages != null) {
18919                synchronized (mPackages) {
18920                    final int childCount = outInfo.removedChildPackages.size();
18921                    for (int i = 0; i < childCount; i++) {
18922                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18923                        if (childInfo != null) {
18924                            childInfo.removedForAllUsers = mPackages.get(
18925                                    childInfo.removedPackage) == null;
18926                        }
18927                    }
18928                }
18929            }
18930            // If we uninstalled an update to a system app there may be some
18931            // child packages that appeared as they are declared in the system
18932            // app but were not declared in the update.
18933            if (isSystemApp(ps)) {
18934                synchronized (mPackages) {
18935                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18936                    final int childCount = (updatedPs.childPackageNames != null)
18937                            ? updatedPs.childPackageNames.size() : 0;
18938                    for (int i = 0; i < childCount; i++) {
18939                        String childPackageName = updatedPs.childPackageNames.get(i);
18940                        if (outInfo.removedChildPackages == null
18941                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18942                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18943                            if (childPs == null) {
18944                                continue;
18945                            }
18946                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18947                            installRes.name = childPackageName;
18948                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18949                            installRes.pkg = mPackages.get(childPackageName);
18950                            installRes.uid = childPs.pkg.applicationInfo.uid;
18951                            if (outInfo.appearedChildPackages == null) {
18952                                outInfo.appearedChildPackages = new ArrayMap<>();
18953                            }
18954                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18955                        }
18956                    }
18957                }
18958            }
18959        }
18960
18961        return ret;
18962    }
18963
18964    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18965        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18966                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18967        for (int nextUserId : userIds) {
18968            if (DEBUG_REMOVE) {
18969                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18970            }
18971            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18972                    false /*installed*/,
18973                    true /*stopped*/,
18974                    true /*notLaunched*/,
18975                    false /*hidden*/,
18976                    false /*suspended*/,
18977                    false /*instantApp*/,
18978                    false /*virtualPreload*/,
18979                    null /*lastDisableAppCaller*/,
18980                    null /*enabledComponents*/,
18981                    null /*disabledComponents*/,
18982                    ps.readUserState(nextUserId).domainVerificationStatus,
18983                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18984        }
18985        mSettings.writeKernelMappingLPr(ps);
18986    }
18987
18988    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18989            PackageRemovedInfo outInfo) {
18990        final PackageParser.Package pkg;
18991        synchronized (mPackages) {
18992            pkg = mPackages.get(ps.name);
18993        }
18994
18995        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18996                : new int[] {userId};
18997        for (int nextUserId : userIds) {
18998            if (DEBUG_REMOVE) {
18999                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19000                        + nextUserId);
19001            }
19002
19003            destroyAppDataLIF(pkg, userId,
19004                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19005            destroyAppProfilesLIF(pkg, userId);
19006            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19007            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19008            schedulePackageCleaning(ps.name, nextUserId, false);
19009            synchronized (mPackages) {
19010                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19011                    scheduleWritePackageRestrictionsLocked(nextUserId);
19012                }
19013                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19014            }
19015        }
19016
19017        if (outInfo != null) {
19018            outInfo.removedPackage = ps.name;
19019            outInfo.installerPackageName = ps.installerPackageName;
19020            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19021            outInfo.removedAppId = ps.appId;
19022            outInfo.removedUsers = userIds;
19023            outInfo.broadcastUsers = userIds;
19024        }
19025
19026        return true;
19027    }
19028
19029    private final class ClearStorageConnection implements ServiceConnection {
19030        IMediaContainerService mContainerService;
19031
19032        @Override
19033        public void onServiceConnected(ComponentName name, IBinder service) {
19034            synchronized (this) {
19035                mContainerService = IMediaContainerService.Stub
19036                        .asInterface(Binder.allowBlocking(service));
19037                notifyAll();
19038            }
19039        }
19040
19041        @Override
19042        public void onServiceDisconnected(ComponentName name) {
19043        }
19044    }
19045
19046    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19047        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19048
19049        final boolean mounted;
19050        if (Environment.isExternalStorageEmulated()) {
19051            mounted = true;
19052        } else {
19053            final String status = Environment.getExternalStorageState();
19054
19055            mounted = status.equals(Environment.MEDIA_MOUNTED)
19056                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19057        }
19058
19059        if (!mounted) {
19060            return;
19061        }
19062
19063        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19064        int[] users;
19065        if (userId == UserHandle.USER_ALL) {
19066            users = sUserManager.getUserIds();
19067        } else {
19068            users = new int[] { userId };
19069        }
19070        final ClearStorageConnection conn = new ClearStorageConnection();
19071        if (mContext.bindServiceAsUser(
19072                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19073            try {
19074                for (int curUser : users) {
19075                    long timeout = SystemClock.uptimeMillis() + 5000;
19076                    synchronized (conn) {
19077                        long now;
19078                        while (conn.mContainerService == null &&
19079                                (now = SystemClock.uptimeMillis()) < timeout) {
19080                            try {
19081                                conn.wait(timeout - now);
19082                            } catch (InterruptedException e) {
19083                            }
19084                        }
19085                    }
19086                    if (conn.mContainerService == null) {
19087                        return;
19088                    }
19089
19090                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19091                    clearDirectory(conn.mContainerService,
19092                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19093                    if (allData) {
19094                        clearDirectory(conn.mContainerService,
19095                                userEnv.buildExternalStorageAppDataDirs(packageName));
19096                        clearDirectory(conn.mContainerService,
19097                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19098                    }
19099                }
19100            } finally {
19101                mContext.unbindService(conn);
19102            }
19103        }
19104    }
19105
19106    @Override
19107    public void clearApplicationProfileData(String packageName) {
19108        enforceSystemOrRoot("Only the system can clear all profile data");
19109
19110        final PackageParser.Package pkg;
19111        synchronized (mPackages) {
19112            pkg = mPackages.get(packageName);
19113        }
19114
19115        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19116            synchronized (mInstallLock) {
19117                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19118            }
19119        }
19120    }
19121
19122    @Override
19123    public void clearApplicationUserData(final String packageName,
19124            final IPackageDataObserver observer, final int userId) {
19125        mContext.enforceCallingOrSelfPermission(
19126                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19127
19128        final int callingUid = Binder.getCallingUid();
19129        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19130                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19131
19132        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19133        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
19134        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19135            throw new SecurityException("Cannot clear data for a protected package: "
19136                    + packageName);
19137        }
19138        // Queue up an async operation since the package deletion may take a little while.
19139        mHandler.post(new Runnable() {
19140            public void run() {
19141                mHandler.removeCallbacks(this);
19142                final boolean succeeded;
19143                if (!filterApp) {
19144                    try (PackageFreezer freezer = freezePackage(packageName,
19145                            "clearApplicationUserData")) {
19146                        synchronized (mInstallLock) {
19147                            succeeded = clearApplicationUserDataLIF(packageName, userId);
19148                        }
19149                        clearExternalStorageDataSync(packageName, userId, true);
19150                        synchronized (mPackages) {
19151                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19152                                    packageName, userId);
19153                        }
19154                    }
19155                    if (succeeded) {
19156                        // invoke DeviceStorageMonitor's update method to clear any notifications
19157                        DeviceStorageMonitorInternal dsm = LocalServices
19158                                .getService(DeviceStorageMonitorInternal.class);
19159                        if (dsm != null) {
19160                            dsm.checkMemory();
19161                        }
19162                    }
19163                } else {
19164                    succeeded = false;
19165                }
19166                if (observer != null) {
19167                    try {
19168                        observer.onRemoveCompleted(packageName, succeeded);
19169                    } catch (RemoteException e) {
19170                        Log.i(TAG, "Observer no longer exists.");
19171                    }
19172                } //end if observer
19173            } //end run
19174        });
19175    }
19176
19177    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19178        if (packageName == null) {
19179            Slog.w(TAG, "Attempt to delete null packageName.");
19180            return false;
19181        }
19182
19183        // Try finding details about the requested package
19184        PackageParser.Package pkg;
19185        synchronized (mPackages) {
19186            pkg = mPackages.get(packageName);
19187            if (pkg == null) {
19188                final PackageSetting ps = mSettings.mPackages.get(packageName);
19189                if (ps != null) {
19190                    pkg = ps.pkg;
19191                }
19192            }
19193
19194            if (pkg == null) {
19195                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19196                return false;
19197            }
19198
19199            PackageSetting ps = (PackageSetting) pkg.mExtras;
19200            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19201        }
19202
19203        clearAppDataLIF(pkg, userId,
19204                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19205
19206        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19207        removeKeystoreDataIfNeeded(userId, appId);
19208
19209        UserManagerInternal umInternal = getUserManagerInternal();
19210        final int flags;
19211        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19212            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19213        } else if (umInternal.isUserRunning(userId)) {
19214            flags = StorageManager.FLAG_STORAGE_DE;
19215        } else {
19216            flags = 0;
19217        }
19218        prepareAppDataContentsLIF(pkg, userId, flags);
19219
19220        return true;
19221    }
19222
19223    /**
19224     * Reverts user permission state changes (permissions and flags) in
19225     * all packages for a given user.
19226     *
19227     * @param userId The device user for which to do a reset.
19228     */
19229    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19230        final int packageCount = mPackages.size();
19231        for (int i = 0; i < packageCount; i++) {
19232            PackageParser.Package pkg = mPackages.valueAt(i);
19233            PackageSetting ps = (PackageSetting) pkg.mExtras;
19234            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19235        }
19236    }
19237
19238    private void resetNetworkPolicies(int userId) {
19239        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19240    }
19241
19242    /**
19243     * Reverts user permission state changes (permissions and flags).
19244     *
19245     * @param ps The package for which to reset.
19246     * @param userId The device user for which to do a reset.
19247     */
19248    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19249            final PackageSetting ps, final int userId) {
19250        if (ps.pkg == null) {
19251            return;
19252        }
19253
19254        // These are flags that can change base on user actions.
19255        final int userSettableMask = FLAG_PERMISSION_USER_SET
19256                | FLAG_PERMISSION_USER_FIXED
19257                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19258                | FLAG_PERMISSION_REVIEW_REQUIRED;
19259
19260        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19261                | FLAG_PERMISSION_POLICY_FIXED;
19262
19263        boolean writeInstallPermissions = false;
19264        boolean writeRuntimePermissions = false;
19265
19266        final int permissionCount = ps.pkg.requestedPermissions.size();
19267        for (int i = 0; i < permissionCount; i++) {
19268            final String permName = ps.pkg.requestedPermissions.get(i);
19269            final BasePermission bp =
19270                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19271            if (bp == null) {
19272                continue;
19273            }
19274
19275            // If shared user we just reset the state to which only this app contributed.
19276            if (ps.sharedUser != null) {
19277                boolean used = false;
19278                final int packageCount = ps.sharedUser.packages.size();
19279                for (int j = 0; j < packageCount; j++) {
19280                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19281                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19282                            && pkg.pkg.requestedPermissions.contains(permName)) {
19283                        used = true;
19284                        break;
19285                    }
19286                }
19287                if (used) {
19288                    continue;
19289                }
19290            }
19291
19292            final PermissionsState permissionsState = ps.getPermissionsState();
19293
19294            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19295
19296            // Always clear the user settable flags.
19297            final boolean hasInstallState =
19298                    permissionsState.getInstallPermissionState(permName) != null;
19299            // If permission review is enabled and this is a legacy app, mark the
19300            // permission as requiring a review as this is the initial state.
19301            int flags = 0;
19302            if (mPermissionReviewRequired
19303                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19304                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19305            }
19306            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19307                if (hasInstallState) {
19308                    writeInstallPermissions = true;
19309                } else {
19310                    writeRuntimePermissions = true;
19311                }
19312            }
19313
19314            // Below is only runtime permission handling.
19315            if (!bp.isRuntime()) {
19316                continue;
19317            }
19318
19319            // Never clobber system or policy.
19320            if ((oldFlags & policyOrSystemFlags) != 0) {
19321                continue;
19322            }
19323
19324            // If this permission was granted by default, make sure it is.
19325            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19326                if (permissionsState.grantRuntimePermission(bp, userId)
19327                        != PERMISSION_OPERATION_FAILURE) {
19328                    writeRuntimePermissions = true;
19329                }
19330            // If permission review is enabled the permissions for a legacy apps
19331            // are represented as constantly granted runtime ones, so don't revoke.
19332            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19333                // Otherwise, reset the permission.
19334                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19335                switch (revokeResult) {
19336                    case PERMISSION_OPERATION_SUCCESS:
19337                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19338                        writeRuntimePermissions = true;
19339                        final int appId = ps.appId;
19340                        mHandler.post(new Runnable() {
19341                            @Override
19342                            public void run() {
19343                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19344                            }
19345                        });
19346                    } break;
19347                }
19348            }
19349        }
19350
19351        // Synchronously write as we are taking permissions away.
19352        if (writeRuntimePermissions) {
19353            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19354        }
19355
19356        // Synchronously write as we are taking permissions away.
19357        if (writeInstallPermissions) {
19358            mSettings.writeLPr();
19359        }
19360    }
19361
19362    /**
19363     * Remove entries from the keystore daemon. Will only remove it if the
19364     * {@code appId} is valid.
19365     */
19366    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19367        if (appId < 0) {
19368            return;
19369        }
19370
19371        final KeyStore keyStore = KeyStore.getInstance();
19372        if (keyStore != null) {
19373            if (userId == UserHandle.USER_ALL) {
19374                for (final int individual : sUserManager.getUserIds()) {
19375                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19376                }
19377            } else {
19378                keyStore.clearUid(UserHandle.getUid(userId, appId));
19379            }
19380        } else {
19381            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19382        }
19383    }
19384
19385    @Override
19386    public void deleteApplicationCacheFiles(final String packageName,
19387            final IPackageDataObserver observer) {
19388        final int userId = UserHandle.getCallingUserId();
19389        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19390    }
19391
19392    @Override
19393    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19394            final IPackageDataObserver observer) {
19395        final int callingUid = Binder.getCallingUid();
19396        mContext.enforceCallingOrSelfPermission(
19397                android.Manifest.permission.DELETE_CACHE_FILES, null);
19398        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19399                /* requireFullPermission= */ true, /* checkShell= */ false,
19400                "delete application cache files");
19401        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19402                android.Manifest.permission.ACCESS_INSTANT_APPS);
19403
19404        final PackageParser.Package pkg;
19405        synchronized (mPackages) {
19406            pkg = mPackages.get(packageName);
19407        }
19408
19409        // Queue up an async operation since the package deletion may take a little while.
19410        mHandler.post(new Runnable() {
19411            public void run() {
19412                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19413                boolean doClearData = true;
19414                if (ps != null) {
19415                    final boolean targetIsInstantApp =
19416                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19417                    doClearData = !targetIsInstantApp
19418                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19419                }
19420                if (doClearData) {
19421                    synchronized (mInstallLock) {
19422                        final int flags = StorageManager.FLAG_STORAGE_DE
19423                                | StorageManager.FLAG_STORAGE_CE;
19424                        // We're only clearing cache files, so we don't care if the
19425                        // app is unfrozen and still able to run
19426                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19427                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19428                    }
19429                    clearExternalStorageDataSync(packageName, userId, false);
19430                }
19431                if (observer != null) {
19432                    try {
19433                        observer.onRemoveCompleted(packageName, true);
19434                    } catch (RemoteException e) {
19435                        Log.i(TAG, "Observer no longer exists.");
19436                    }
19437                }
19438            }
19439        });
19440    }
19441
19442    @Override
19443    public void getPackageSizeInfo(final String packageName, int userHandle,
19444            final IPackageStatsObserver observer) {
19445        throw new UnsupportedOperationException(
19446                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19447    }
19448
19449    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19450        final PackageSetting ps;
19451        synchronized (mPackages) {
19452            ps = mSettings.mPackages.get(packageName);
19453            if (ps == null) {
19454                Slog.w(TAG, "Failed to find settings for " + packageName);
19455                return false;
19456            }
19457        }
19458
19459        final String[] packageNames = { packageName };
19460        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19461        final String[] codePaths = { ps.codePathString };
19462
19463        try {
19464            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19465                    ps.appId, ceDataInodes, codePaths, stats);
19466
19467            // For now, ignore code size of packages on system partition
19468            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19469                stats.codeSize = 0;
19470            }
19471
19472            // External clients expect these to be tracked separately
19473            stats.dataSize -= stats.cacheSize;
19474
19475        } catch (InstallerException e) {
19476            Slog.w(TAG, String.valueOf(e));
19477            return false;
19478        }
19479
19480        return true;
19481    }
19482
19483    private int getUidTargetSdkVersionLockedLPr(int uid) {
19484        Object obj = mSettings.getUserIdLPr(uid);
19485        if (obj instanceof SharedUserSetting) {
19486            final SharedUserSetting sus = (SharedUserSetting) obj;
19487            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19488            final Iterator<PackageSetting> it = sus.packages.iterator();
19489            while (it.hasNext()) {
19490                final PackageSetting ps = it.next();
19491                if (ps.pkg != null) {
19492                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19493                    if (v < vers) vers = v;
19494                }
19495            }
19496            return vers;
19497        } else if (obj instanceof PackageSetting) {
19498            final PackageSetting ps = (PackageSetting) obj;
19499            if (ps.pkg != null) {
19500                return ps.pkg.applicationInfo.targetSdkVersion;
19501            }
19502        }
19503        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19504    }
19505
19506    @Override
19507    public void addPreferredActivity(IntentFilter filter, int match,
19508            ComponentName[] set, ComponentName activity, int userId) {
19509        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19510                "Adding preferred");
19511    }
19512
19513    private void addPreferredActivityInternal(IntentFilter filter, int match,
19514            ComponentName[] set, ComponentName activity, boolean always, int userId,
19515            String opname) {
19516        // writer
19517        int callingUid = Binder.getCallingUid();
19518        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19519                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19520        if (filter.countActions() == 0) {
19521            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19522            return;
19523        }
19524        synchronized (mPackages) {
19525            if (mContext.checkCallingOrSelfPermission(
19526                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19527                    != PackageManager.PERMISSION_GRANTED) {
19528                if (getUidTargetSdkVersionLockedLPr(callingUid)
19529                        < Build.VERSION_CODES.FROYO) {
19530                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19531                            + callingUid);
19532                    return;
19533                }
19534                mContext.enforceCallingOrSelfPermission(
19535                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19536            }
19537
19538            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19539            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19540                    + userId + ":");
19541            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19542            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19543            scheduleWritePackageRestrictionsLocked(userId);
19544            postPreferredActivityChangedBroadcast(userId);
19545        }
19546    }
19547
19548    private void postPreferredActivityChangedBroadcast(int userId) {
19549        mHandler.post(() -> {
19550            final IActivityManager am = ActivityManager.getService();
19551            if (am == null) {
19552                return;
19553            }
19554
19555            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19556            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19557            try {
19558                am.broadcastIntent(null, intent, null, null,
19559                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19560                        null, false, false, userId);
19561            } catch (RemoteException e) {
19562            }
19563        });
19564    }
19565
19566    @Override
19567    public void replacePreferredActivity(IntentFilter filter, int match,
19568            ComponentName[] set, ComponentName activity, int userId) {
19569        if (filter.countActions() != 1) {
19570            throw new IllegalArgumentException(
19571                    "replacePreferredActivity expects filter to have only 1 action.");
19572        }
19573        if (filter.countDataAuthorities() != 0
19574                || filter.countDataPaths() != 0
19575                || filter.countDataSchemes() > 1
19576                || filter.countDataTypes() != 0) {
19577            throw new IllegalArgumentException(
19578                    "replacePreferredActivity expects filter to have no data authorities, " +
19579                    "paths, or types; and at most one scheme.");
19580        }
19581
19582        final int callingUid = Binder.getCallingUid();
19583        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19584                true /* requireFullPermission */, false /* checkShell */,
19585                "replace preferred activity");
19586        synchronized (mPackages) {
19587            if (mContext.checkCallingOrSelfPermission(
19588                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19589                    != PackageManager.PERMISSION_GRANTED) {
19590                if (getUidTargetSdkVersionLockedLPr(callingUid)
19591                        < Build.VERSION_CODES.FROYO) {
19592                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19593                            + Binder.getCallingUid());
19594                    return;
19595                }
19596                mContext.enforceCallingOrSelfPermission(
19597                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19598            }
19599
19600            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19601            if (pir != null) {
19602                // Get all of the existing entries that exactly match this filter.
19603                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19604                if (existing != null && existing.size() == 1) {
19605                    PreferredActivity cur = existing.get(0);
19606                    if (DEBUG_PREFERRED) {
19607                        Slog.i(TAG, "Checking replace of preferred:");
19608                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19609                        if (!cur.mPref.mAlways) {
19610                            Slog.i(TAG, "  -- CUR; not mAlways!");
19611                        } else {
19612                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19613                            Slog.i(TAG, "  -- CUR: mSet="
19614                                    + Arrays.toString(cur.mPref.mSetComponents));
19615                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19616                            Slog.i(TAG, "  -- NEW: mMatch="
19617                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19618                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19619                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19620                        }
19621                    }
19622                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19623                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19624                            && cur.mPref.sameSet(set)) {
19625                        // Setting the preferred activity to what it happens to be already
19626                        if (DEBUG_PREFERRED) {
19627                            Slog.i(TAG, "Replacing with same preferred activity "
19628                                    + cur.mPref.mShortComponent + " for user "
19629                                    + userId + ":");
19630                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19631                        }
19632                        return;
19633                    }
19634                }
19635
19636                if (existing != null) {
19637                    if (DEBUG_PREFERRED) {
19638                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19639                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19640                    }
19641                    for (int i = 0; i < existing.size(); i++) {
19642                        PreferredActivity pa = existing.get(i);
19643                        if (DEBUG_PREFERRED) {
19644                            Slog.i(TAG, "Removing existing preferred activity "
19645                                    + pa.mPref.mComponent + ":");
19646                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19647                        }
19648                        pir.removeFilter(pa);
19649                    }
19650                }
19651            }
19652            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19653                    "Replacing preferred");
19654        }
19655    }
19656
19657    @Override
19658    public void clearPackagePreferredActivities(String packageName) {
19659        final int callingUid = Binder.getCallingUid();
19660        if (getInstantAppPackageName(callingUid) != null) {
19661            return;
19662        }
19663        // writer
19664        synchronized (mPackages) {
19665            PackageParser.Package pkg = mPackages.get(packageName);
19666            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19667                if (mContext.checkCallingOrSelfPermission(
19668                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19669                        != PackageManager.PERMISSION_GRANTED) {
19670                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19671                            < Build.VERSION_CODES.FROYO) {
19672                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19673                                + callingUid);
19674                        return;
19675                    }
19676                    mContext.enforceCallingOrSelfPermission(
19677                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19678                }
19679            }
19680            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19681            if (ps != null
19682                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19683                return;
19684            }
19685            int user = UserHandle.getCallingUserId();
19686            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19687                scheduleWritePackageRestrictionsLocked(user);
19688            }
19689        }
19690    }
19691
19692    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19693    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19694        ArrayList<PreferredActivity> removed = null;
19695        boolean changed = false;
19696        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19697            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19698            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19699            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19700                continue;
19701            }
19702            Iterator<PreferredActivity> it = pir.filterIterator();
19703            while (it.hasNext()) {
19704                PreferredActivity pa = it.next();
19705                // Mark entry for removal only if it matches the package name
19706                // and the entry is of type "always".
19707                if (packageName == null ||
19708                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19709                                && pa.mPref.mAlways)) {
19710                    if (removed == null) {
19711                        removed = new ArrayList<PreferredActivity>();
19712                    }
19713                    removed.add(pa);
19714                }
19715            }
19716            if (removed != null) {
19717                for (int j=0; j<removed.size(); j++) {
19718                    PreferredActivity pa = removed.get(j);
19719                    pir.removeFilter(pa);
19720                }
19721                changed = true;
19722            }
19723        }
19724        if (changed) {
19725            postPreferredActivityChangedBroadcast(userId);
19726        }
19727        return changed;
19728    }
19729
19730    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19731    private void clearIntentFilterVerificationsLPw(int userId) {
19732        final int packageCount = mPackages.size();
19733        for (int i = 0; i < packageCount; i++) {
19734            PackageParser.Package pkg = mPackages.valueAt(i);
19735            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19736        }
19737    }
19738
19739    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19740    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19741        if (userId == UserHandle.USER_ALL) {
19742            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19743                    sUserManager.getUserIds())) {
19744                for (int oneUserId : sUserManager.getUserIds()) {
19745                    scheduleWritePackageRestrictionsLocked(oneUserId);
19746                }
19747            }
19748        } else {
19749            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19750                scheduleWritePackageRestrictionsLocked(userId);
19751            }
19752        }
19753    }
19754
19755    /** Clears state for all users, and touches intent filter verification policy */
19756    void clearDefaultBrowserIfNeeded(String packageName) {
19757        for (int oneUserId : sUserManager.getUserIds()) {
19758            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19759        }
19760    }
19761
19762    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19763        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19764        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19765            if (packageName.equals(defaultBrowserPackageName)) {
19766                setDefaultBrowserPackageName(null, userId);
19767            }
19768        }
19769    }
19770
19771    @Override
19772    public void resetApplicationPreferences(int userId) {
19773        mContext.enforceCallingOrSelfPermission(
19774                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19775        final long identity = Binder.clearCallingIdentity();
19776        // writer
19777        try {
19778            synchronized (mPackages) {
19779                clearPackagePreferredActivitiesLPw(null, userId);
19780                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19781                // TODO: We have to reset the default SMS and Phone. This requires
19782                // significant refactoring to keep all default apps in the package
19783                // manager (cleaner but more work) or have the services provide
19784                // callbacks to the package manager to request a default app reset.
19785                applyFactoryDefaultBrowserLPw(userId);
19786                clearIntentFilterVerificationsLPw(userId);
19787                primeDomainVerificationsLPw(userId);
19788                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19789                scheduleWritePackageRestrictionsLocked(userId);
19790            }
19791            resetNetworkPolicies(userId);
19792        } finally {
19793            Binder.restoreCallingIdentity(identity);
19794        }
19795    }
19796
19797    @Override
19798    public int getPreferredActivities(List<IntentFilter> outFilters,
19799            List<ComponentName> outActivities, String packageName) {
19800        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19801            return 0;
19802        }
19803        int num = 0;
19804        final int userId = UserHandle.getCallingUserId();
19805        // reader
19806        synchronized (mPackages) {
19807            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19808            if (pir != null) {
19809                final Iterator<PreferredActivity> it = pir.filterIterator();
19810                while (it.hasNext()) {
19811                    final PreferredActivity pa = it.next();
19812                    if (packageName == null
19813                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19814                                    && pa.mPref.mAlways)) {
19815                        if (outFilters != null) {
19816                            outFilters.add(new IntentFilter(pa));
19817                        }
19818                        if (outActivities != null) {
19819                            outActivities.add(pa.mPref.mComponent);
19820                        }
19821                    }
19822                }
19823            }
19824        }
19825
19826        return num;
19827    }
19828
19829    @Override
19830    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19831            int userId) {
19832        int callingUid = Binder.getCallingUid();
19833        if (callingUid != Process.SYSTEM_UID) {
19834            throw new SecurityException(
19835                    "addPersistentPreferredActivity can only be run by the system");
19836        }
19837        if (filter.countActions() == 0) {
19838            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19839            return;
19840        }
19841        synchronized (mPackages) {
19842            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19843                    ":");
19844            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19845            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19846                    new PersistentPreferredActivity(filter, activity));
19847            scheduleWritePackageRestrictionsLocked(userId);
19848            postPreferredActivityChangedBroadcast(userId);
19849        }
19850    }
19851
19852    @Override
19853    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19854        int callingUid = Binder.getCallingUid();
19855        if (callingUid != Process.SYSTEM_UID) {
19856            throw new SecurityException(
19857                    "clearPackagePersistentPreferredActivities can only be run by the system");
19858        }
19859        ArrayList<PersistentPreferredActivity> removed = null;
19860        boolean changed = false;
19861        synchronized (mPackages) {
19862            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19863                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19864                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19865                        .valueAt(i);
19866                if (userId != thisUserId) {
19867                    continue;
19868                }
19869                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19870                while (it.hasNext()) {
19871                    PersistentPreferredActivity ppa = it.next();
19872                    // Mark entry for removal only if it matches the package name.
19873                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19874                        if (removed == null) {
19875                            removed = new ArrayList<PersistentPreferredActivity>();
19876                        }
19877                        removed.add(ppa);
19878                    }
19879                }
19880                if (removed != null) {
19881                    for (int j=0; j<removed.size(); j++) {
19882                        PersistentPreferredActivity ppa = removed.get(j);
19883                        ppir.removeFilter(ppa);
19884                    }
19885                    changed = true;
19886                }
19887            }
19888
19889            if (changed) {
19890                scheduleWritePackageRestrictionsLocked(userId);
19891                postPreferredActivityChangedBroadcast(userId);
19892            }
19893        }
19894    }
19895
19896    /**
19897     * Common machinery for picking apart a restored XML blob and passing
19898     * it to a caller-supplied functor to be applied to the running system.
19899     */
19900    private void restoreFromXml(XmlPullParser parser, int userId,
19901            String expectedStartTag, BlobXmlRestorer functor)
19902            throws IOException, XmlPullParserException {
19903        int type;
19904        while ((type = parser.next()) != XmlPullParser.START_TAG
19905                && type != XmlPullParser.END_DOCUMENT) {
19906        }
19907        if (type != XmlPullParser.START_TAG) {
19908            // oops didn't find a start tag?!
19909            if (DEBUG_BACKUP) {
19910                Slog.e(TAG, "Didn't find start tag during restore");
19911            }
19912            return;
19913        }
19914Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19915        // this is supposed to be TAG_PREFERRED_BACKUP
19916        if (!expectedStartTag.equals(parser.getName())) {
19917            if (DEBUG_BACKUP) {
19918                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19919            }
19920            return;
19921        }
19922
19923        // skip interfering stuff, then we're aligned with the backing implementation
19924        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19925Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19926        functor.apply(parser, userId);
19927    }
19928
19929    private interface BlobXmlRestorer {
19930        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19931    }
19932
19933    /**
19934     * Non-Binder method, support for the backup/restore mechanism: write the
19935     * full set of preferred activities in its canonical XML format.  Returns the
19936     * XML output as a byte array, or null if there is none.
19937     */
19938    @Override
19939    public byte[] getPreferredActivityBackup(int userId) {
19940        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19941            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19942        }
19943
19944        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19945        try {
19946            final XmlSerializer serializer = new FastXmlSerializer();
19947            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19948            serializer.startDocument(null, true);
19949            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19950
19951            synchronized (mPackages) {
19952                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19953            }
19954
19955            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19956            serializer.endDocument();
19957            serializer.flush();
19958        } catch (Exception e) {
19959            if (DEBUG_BACKUP) {
19960                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19961            }
19962            return null;
19963        }
19964
19965        return dataStream.toByteArray();
19966    }
19967
19968    @Override
19969    public void restorePreferredActivities(byte[] backup, int userId) {
19970        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19971            throw new SecurityException("Only the system may call restorePreferredActivities()");
19972        }
19973
19974        try {
19975            final XmlPullParser parser = Xml.newPullParser();
19976            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19977            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19978                    new BlobXmlRestorer() {
19979                        @Override
19980                        public void apply(XmlPullParser parser, int userId)
19981                                throws XmlPullParserException, IOException {
19982                            synchronized (mPackages) {
19983                                mSettings.readPreferredActivitiesLPw(parser, userId);
19984                            }
19985                        }
19986                    } );
19987        } catch (Exception e) {
19988            if (DEBUG_BACKUP) {
19989                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19990            }
19991        }
19992    }
19993
19994    /**
19995     * Non-Binder method, support for the backup/restore mechanism: write the
19996     * default browser (etc) settings in its canonical XML format.  Returns the default
19997     * browser XML representation as a byte array, or null if there is none.
19998     */
19999    @Override
20000    public byte[] getDefaultAppsBackup(int userId) {
20001        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20002            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20003        }
20004
20005        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20006        try {
20007            final XmlSerializer serializer = new FastXmlSerializer();
20008            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20009            serializer.startDocument(null, true);
20010            serializer.startTag(null, TAG_DEFAULT_APPS);
20011
20012            synchronized (mPackages) {
20013                mSettings.writeDefaultAppsLPr(serializer, userId);
20014            }
20015
20016            serializer.endTag(null, TAG_DEFAULT_APPS);
20017            serializer.endDocument();
20018            serializer.flush();
20019        } catch (Exception e) {
20020            if (DEBUG_BACKUP) {
20021                Slog.e(TAG, "Unable to write default apps for backup", e);
20022            }
20023            return null;
20024        }
20025
20026        return dataStream.toByteArray();
20027    }
20028
20029    @Override
20030    public void restoreDefaultApps(byte[] backup, int userId) {
20031        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20032            throw new SecurityException("Only the system may call restoreDefaultApps()");
20033        }
20034
20035        try {
20036            final XmlPullParser parser = Xml.newPullParser();
20037            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20038            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20039                    new BlobXmlRestorer() {
20040                        @Override
20041                        public void apply(XmlPullParser parser, int userId)
20042                                throws XmlPullParserException, IOException {
20043                            synchronized (mPackages) {
20044                                mSettings.readDefaultAppsLPw(parser, userId);
20045                            }
20046                        }
20047                    } );
20048        } catch (Exception e) {
20049            if (DEBUG_BACKUP) {
20050                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20051            }
20052        }
20053    }
20054
20055    @Override
20056    public byte[] getIntentFilterVerificationBackup(int userId) {
20057        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20058            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20059        }
20060
20061        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20062        try {
20063            final XmlSerializer serializer = new FastXmlSerializer();
20064            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20065            serializer.startDocument(null, true);
20066            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20067
20068            synchronized (mPackages) {
20069                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20070            }
20071
20072            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20073            serializer.endDocument();
20074            serializer.flush();
20075        } catch (Exception e) {
20076            if (DEBUG_BACKUP) {
20077                Slog.e(TAG, "Unable to write default apps for backup", e);
20078            }
20079            return null;
20080        }
20081
20082        return dataStream.toByteArray();
20083    }
20084
20085    @Override
20086    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20087        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20088            throw new SecurityException("Only the system may call restorePreferredActivities()");
20089        }
20090
20091        try {
20092            final XmlPullParser parser = Xml.newPullParser();
20093            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20094            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20095                    new BlobXmlRestorer() {
20096                        @Override
20097                        public void apply(XmlPullParser parser, int userId)
20098                                throws XmlPullParserException, IOException {
20099                            synchronized (mPackages) {
20100                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20101                                mSettings.writeLPr();
20102                            }
20103                        }
20104                    } );
20105        } catch (Exception e) {
20106            if (DEBUG_BACKUP) {
20107                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20108            }
20109        }
20110    }
20111
20112    @Override
20113    public byte[] getPermissionGrantBackup(int userId) {
20114        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20115            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20116        }
20117
20118        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20119        try {
20120            final XmlSerializer serializer = new FastXmlSerializer();
20121            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20122            serializer.startDocument(null, true);
20123            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20124
20125            synchronized (mPackages) {
20126                serializeRuntimePermissionGrantsLPr(serializer, userId);
20127            }
20128
20129            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20130            serializer.endDocument();
20131            serializer.flush();
20132        } catch (Exception e) {
20133            if (DEBUG_BACKUP) {
20134                Slog.e(TAG, "Unable to write default apps for backup", e);
20135            }
20136            return null;
20137        }
20138
20139        return dataStream.toByteArray();
20140    }
20141
20142    @Override
20143    public void restorePermissionGrants(byte[] backup, int userId) {
20144        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20145            throw new SecurityException("Only the system may call restorePermissionGrants()");
20146        }
20147
20148        try {
20149            final XmlPullParser parser = Xml.newPullParser();
20150            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20151            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20152                    new BlobXmlRestorer() {
20153                        @Override
20154                        public void apply(XmlPullParser parser, int userId)
20155                                throws XmlPullParserException, IOException {
20156                            synchronized (mPackages) {
20157                                processRestoredPermissionGrantsLPr(parser, userId);
20158                            }
20159                        }
20160                    } );
20161        } catch (Exception e) {
20162            if (DEBUG_BACKUP) {
20163                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20164            }
20165        }
20166    }
20167
20168    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20169            throws IOException {
20170        serializer.startTag(null, TAG_ALL_GRANTS);
20171
20172        final int N = mSettings.mPackages.size();
20173        for (int i = 0; i < N; i++) {
20174            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20175            boolean pkgGrantsKnown = false;
20176
20177            PermissionsState packagePerms = ps.getPermissionsState();
20178
20179            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20180                final int grantFlags = state.getFlags();
20181                // only look at grants that are not system/policy fixed
20182                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20183                    final boolean isGranted = state.isGranted();
20184                    // And only back up the user-twiddled state bits
20185                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20186                        final String packageName = mSettings.mPackages.keyAt(i);
20187                        if (!pkgGrantsKnown) {
20188                            serializer.startTag(null, TAG_GRANT);
20189                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20190                            pkgGrantsKnown = true;
20191                        }
20192
20193                        final boolean userSet =
20194                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20195                        final boolean userFixed =
20196                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20197                        final boolean revoke =
20198                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20199
20200                        serializer.startTag(null, TAG_PERMISSION);
20201                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20202                        if (isGranted) {
20203                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20204                        }
20205                        if (userSet) {
20206                            serializer.attribute(null, ATTR_USER_SET, "true");
20207                        }
20208                        if (userFixed) {
20209                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20210                        }
20211                        if (revoke) {
20212                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20213                        }
20214                        serializer.endTag(null, TAG_PERMISSION);
20215                    }
20216                }
20217            }
20218
20219            if (pkgGrantsKnown) {
20220                serializer.endTag(null, TAG_GRANT);
20221            }
20222        }
20223
20224        serializer.endTag(null, TAG_ALL_GRANTS);
20225    }
20226
20227    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20228            throws XmlPullParserException, IOException {
20229        String pkgName = null;
20230        int outerDepth = parser.getDepth();
20231        int type;
20232        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20233                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20234            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20235                continue;
20236            }
20237
20238            final String tagName = parser.getName();
20239            if (tagName.equals(TAG_GRANT)) {
20240                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20241                if (DEBUG_BACKUP) {
20242                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20243                }
20244            } else if (tagName.equals(TAG_PERMISSION)) {
20245
20246                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20247                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20248
20249                int newFlagSet = 0;
20250                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20251                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20252                }
20253                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20254                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20255                }
20256                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20257                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20258                }
20259                if (DEBUG_BACKUP) {
20260                    Slog.v(TAG, "  + Restoring grant:"
20261                            + " pkg=" + pkgName
20262                            + " perm=" + permName
20263                            + " granted=" + isGranted
20264                            + " bits=0x" + Integer.toHexString(newFlagSet));
20265                }
20266                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20267                if (ps != null) {
20268                    // Already installed so we apply the grant immediately
20269                    if (DEBUG_BACKUP) {
20270                        Slog.v(TAG, "        + already installed; applying");
20271                    }
20272                    PermissionsState perms = ps.getPermissionsState();
20273                    BasePermission bp =
20274                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
20275                    if (bp != null) {
20276                        if (isGranted) {
20277                            perms.grantRuntimePermission(bp, userId);
20278                        }
20279                        if (newFlagSet != 0) {
20280                            perms.updatePermissionFlags(
20281                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20282                        }
20283                    }
20284                } else {
20285                    // Need to wait for post-restore install to apply the grant
20286                    if (DEBUG_BACKUP) {
20287                        Slog.v(TAG, "        - not yet installed; saving for later");
20288                    }
20289                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20290                            isGranted, newFlagSet, userId);
20291                }
20292            } else {
20293                PackageManagerService.reportSettingsProblem(Log.WARN,
20294                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20295                XmlUtils.skipCurrentTag(parser);
20296            }
20297        }
20298
20299        scheduleWriteSettingsLocked();
20300        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20301    }
20302
20303    @Override
20304    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20305            int sourceUserId, int targetUserId, int flags) {
20306        mContext.enforceCallingOrSelfPermission(
20307                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20308        int callingUid = Binder.getCallingUid();
20309        enforceOwnerRights(ownerPackage, callingUid);
20310        PackageManagerServiceUtils.enforceShellRestriction(
20311                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20312        if (intentFilter.countActions() == 0) {
20313            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20314            return;
20315        }
20316        synchronized (mPackages) {
20317            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20318                    ownerPackage, targetUserId, flags);
20319            CrossProfileIntentResolver resolver =
20320                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20321            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20322            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20323            if (existing != null) {
20324                int size = existing.size();
20325                for (int i = 0; i < size; i++) {
20326                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20327                        return;
20328                    }
20329                }
20330            }
20331            resolver.addFilter(newFilter);
20332            scheduleWritePackageRestrictionsLocked(sourceUserId);
20333        }
20334    }
20335
20336    @Override
20337    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20338        mContext.enforceCallingOrSelfPermission(
20339                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20340        final int callingUid = Binder.getCallingUid();
20341        enforceOwnerRights(ownerPackage, callingUid);
20342        PackageManagerServiceUtils.enforceShellRestriction(
20343                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20344        synchronized (mPackages) {
20345            CrossProfileIntentResolver resolver =
20346                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20347            ArraySet<CrossProfileIntentFilter> set =
20348                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20349            for (CrossProfileIntentFilter filter : set) {
20350                if (filter.getOwnerPackage().equals(ownerPackage)) {
20351                    resolver.removeFilter(filter);
20352                }
20353            }
20354            scheduleWritePackageRestrictionsLocked(sourceUserId);
20355        }
20356    }
20357
20358    // Enforcing that callingUid is owning pkg on userId
20359    private void enforceOwnerRights(String pkg, int callingUid) {
20360        // The system owns everything.
20361        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20362            return;
20363        }
20364        final int callingUserId = UserHandle.getUserId(callingUid);
20365        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20366        if (pi == null) {
20367            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20368                    + callingUserId);
20369        }
20370        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20371            throw new SecurityException("Calling uid " + callingUid
20372                    + " does not own package " + pkg);
20373        }
20374    }
20375
20376    @Override
20377    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20378        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20379            return null;
20380        }
20381        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20382    }
20383
20384    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20385        UserManagerService ums = UserManagerService.getInstance();
20386        if (ums != null) {
20387            final UserInfo parent = ums.getProfileParent(userId);
20388            final int launcherUid = (parent != null) ? parent.id : userId;
20389            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20390            if (launcherComponent != null) {
20391                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20392                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20393                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20394                        .setPackage(launcherComponent.getPackageName());
20395                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20396            }
20397        }
20398    }
20399
20400    /**
20401     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20402     * then reports the most likely home activity or null if there are more than one.
20403     */
20404    private ComponentName getDefaultHomeActivity(int userId) {
20405        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20406        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20407        if (cn != null) {
20408            return cn;
20409        }
20410
20411        // Find the launcher with the highest priority and return that component if there are no
20412        // other home activity with the same priority.
20413        int lastPriority = Integer.MIN_VALUE;
20414        ComponentName lastComponent = null;
20415        final int size = allHomeCandidates.size();
20416        for (int i = 0; i < size; i++) {
20417            final ResolveInfo ri = allHomeCandidates.get(i);
20418            if (ri.priority > lastPriority) {
20419                lastComponent = ri.activityInfo.getComponentName();
20420                lastPriority = ri.priority;
20421            } else if (ri.priority == lastPriority) {
20422                // Two components found with same priority.
20423                lastComponent = null;
20424            }
20425        }
20426        return lastComponent;
20427    }
20428
20429    private Intent getHomeIntent() {
20430        Intent intent = new Intent(Intent.ACTION_MAIN);
20431        intent.addCategory(Intent.CATEGORY_HOME);
20432        intent.addCategory(Intent.CATEGORY_DEFAULT);
20433        return intent;
20434    }
20435
20436    private IntentFilter getHomeFilter() {
20437        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20438        filter.addCategory(Intent.CATEGORY_HOME);
20439        filter.addCategory(Intent.CATEGORY_DEFAULT);
20440        return filter;
20441    }
20442
20443    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20444            int userId) {
20445        Intent intent  = getHomeIntent();
20446        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20447                PackageManager.GET_META_DATA, userId);
20448        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20449                true, false, false, userId);
20450
20451        allHomeCandidates.clear();
20452        if (list != null) {
20453            for (ResolveInfo ri : list) {
20454                allHomeCandidates.add(ri);
20455            }
20456        }
20457        return (preferred == null || preferred.activityInfo == null)
20458                ? null
20459                : new ComponentName(preferred.activityInfo.packageName,
20460                        preferred.activityInfo.name);
20461    }
20462
20463    @Override
20464    public void setHomeActivity(ComponentName comp, int userId) {
20465        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20466            return;
20467        }
20468        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20469        getHomeActivitiesAsUser(homeActivities, userId);
20470
20471        boolean found = false;
20472
20473        final int size = homeActivities.size();
20474        final ComponentName[] set = new ComponentName[size];
20475        for (int i = 0; i < size; i++) {
20476            final ResolveInfo candidate = homeActivities.get(i);
20477            final ActivityInfo info = candidate.activityInfo;
20478            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20479            set[i] = activityName;
20480            if (!found && activityName.equals(comp)) {
20481                found = true;
20482            }
20483        }
20484        if (!found) {
20485            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20486                    + userId);
20487        }
20488        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20489                set, comp, userId);
20490    }
20491
20492    private @Nullable String getSetupWizardPackageName() {
20493        final Intent intent = new Intent(Intent.ACTION_MAIN);
20494        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20495
20496        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20497                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20498                        | MATCH_DISABLED_COMPONENTS,
20499                UserHandle.myUserId());
20500        if (matches.size() == 1) {
20501            return matches.get(0).getComponentInfo().packageName;
20502        } else {
20503            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20504                    + ": matches=" + matches);
20505            return null;
20506        }
20507    }
20508
20509    private @Nullable String getStorageManagerPackageName() {
20510        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20511
20512        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20513                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20514                        | MATCH_DISABLED_COMPONENTS,
20515                UserHandle.myUserId());
20516        if (matches.size() == 1) {
20517            return matches.get(0).getComponentInfo().packageName;
20518        } else {
20519            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20520                    + matches.size() + ": matches=" + matches);
20521            return null;
20522        }
20523    }
20524
20525    @Override
20526    public void setApplicationEnabledSetting(String appPackageName,
20527            int newState, int flags, int userId, String callingPackage) {
20528        if (!sUserManager.exists(userId)) return;
20529        if (callingPackage == null) {
20530            callingPackage = Integer.toString(Binder.getCallingUid());
20531        }
20532        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20533    }
20534
20535    @Override
20536    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20537        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20538        synchronized (mPackages) {
20539            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20540            if (pkgSetting != null) {
20541                pkgSetting.setUpdateAvailable(updateAvailable);
20542            }
20543        }
20544    }
20545
20546    @Override
20547    public void setComponentEnabledSetting(ComponentName componentName,
20548            int newState, int flags, int userId) {
20549        if (!sUserManager.exists(userId)) return;
20550        setEnabledSetting(componentName.getPackageName(),
20551                componentName.getClassName(), newState, flags, userId, null);
20552    }
20553
20554    private void setEnabledSetting(final String packageName, String className, int newState,
20555            final int flags, int userId, String callingPackage) {
20556        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20557              || newState == COMPONENT_ENABLED_STATE_ENABLED
20558              || newState == COMPONENT_ENABLED_STATE_DISABLED
20559              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20560              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20561            throw new IllegalArgumentException("Invalid new component state: "
20562                    + newState);
20563        }
20564        PackageSetting pkgSetting;
20565        final int callingUid = Binder.getCallingUid();
20566        final int permission;
20567        if (callingUid == Process.SYSTEM_UID) {
20568            permission = PackageManager.PERMISSION_GRANTED;
20569        } else {
20570            permission = mContext.checkCallingOrSelfPermission(
20571                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20572        }
20573        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20574                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20575        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20576        boolean sendNow = false;
20577        boolean isApp = (className == null);
20578        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20579        String componentName = isApp ? packageName : className;
20580        int packageUid = -1;
20581        ArrayList<String> components;
20582
20583        // reader
20584        synchronized (mPackages) {
20585            pkgSetting = mSettings.mPackages.get(packageName);
20586            if (pkgSetting == null) {
20587                if (!isCallerInstantApp) {
20588                    if (className == null) {
20589                        throw new IllegalArgumentException("Unknown package: " + packageName);
20590                    }
20591                    throw new IllegalArgumentException(
20592                            "Unknown component: " + packageName + "/" + className);
20593                } else {
20594                    // throw SecurityException to prevent leaking package information
20595                    throw new SecurityException(
20596                            "Attempt to change component state; "
20597                            + "pid=" + Binder.getCallingPid()
20598                            + ", uid=" + callingUid
20599                            + (className == null
20600                                    ? ", package=" + packageName
20601                                    : ", component=" + packageName + "/" + className));
20602                }
20603            }
20604        }
20605
20606        // Limit who can change which apps
20607        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20608            // Don't allow apps that don't have permission to modify other apps
20609            if (!allowedByPermission
20610                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20611                throw new SecurityException(
20612                        "Attempt to change component state; "
20613                        + "pid=" + Binder.getCallingPid()
20614                        + ", uid=" + callingUid
20615                        + (className == null
20616                                ? ", package=" + packageName
20617                                : ", component=" + packageName + "/" + className));
20618            }
20619            // Don't allow changing protected packages.
20620            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20621                throw new SecurityException("Cannot disable a protected package: " + packageName);
20622            }
20623        }
20624
20625        synchronized (mPackages) {
20626            if (callingUid == Process.SHELL_UID
20627                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20628                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20629                // unless it is a test package.
20630                int oldState = pkgSetting.getEnabled(userId);
20631                if (className == null
20632                        &&
20633                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20634                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20635                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20636                        &&
20637                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20638                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20639                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20640                    // ok
20641                } else {
20642                    throw new SecurityException(
20643                            "Shell cannot change component state for " + packageName + "/"
20644                                    + className + " to " + newState);
20645                }
20646            }
20647        }
20648        if (className == null) {
20649            // We're dealing with an application/package level state change
20650            synchronized (mPackages) {
20651                if (pkgSetting.getEnabled(userId) == newState) {
20652                    // Nothing to do
20653                    return;
20654                }
20655            }
20656            // If we're enabling a system stub, there's a little more work to do.
20657            // Prior to enabling the package, we need to decompress the APK(s) to the
20658            // data partition and then replace the version on the system partition.
20659            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20660            final boolean isSystemStub = deletedPkg.isStub
20661                    && deletedPkg.isSystemApp();
20662            if (isSystemStub
20663                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20664                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20665                final File codePath = decompressPackage(deletedPkg);
20666                if (codePath == null) {
20667                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20668                    return;
20669                }
20670                // TODO remove direct parsing of the package object during internal cleanup
20671                // of scan package
20672                // We need to call parse directly here for no other reason than we need
20673                // the new package in order to disable the old one [we use the information
20674                // for some internal optimization to optionally create a new package setting
20675                // object on replace]. However, we can't get the package from the scan
20676                // because the scan modifies live structures and we need to remove the
20677                // old [system] package from the system before a scan can be attempted.
20678                // Once scan is indempotent we can remove this parse and use the package
20679                // object we scanned, prior to adding it to package settings.
20680                final PackageParser pp = new PackageParser();
20681                pp.setSeparateProcesses(mSeparateProcesses);
20682                pp.setDisplayMetrics(mMetrics);
20683                pp.setCallback(mPackageParserCallback);
20684                final PackageParser.Package tmpPkg;
20685                try {
20686                    final int parseFlags = mDefParseFlags
20687                            | PackageParser.PARSE_MUST_BE_APK
20688                            | PackageParser.PARSE_IS_SYSTEM
20689                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20690                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20691                } catch (PackageParserException e) {
20692                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20693                    return;
20694                }
20695                synchronized (mInstallLock) {
20696                    // Disable the stub and remove any package entries
20697                    removePackageLI(deletedPkg, true);
20698                    synchronized (mPackages) {
20699                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20700                    }
20701                    final PackageParser.Package newPkg;
20702                    try (PackageFreezer freezer =
20703                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20704                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20705                                | PackageParser.PARSE_ENFORCE_CODE;
20706                        newPkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20707                                0 /*currentTime*/, null /*user*/);
20708                        prepareAppDataAfterInstallLIF(newPkg);
20709                        synchronized (mPackages) {
20710                            try {
20711                                updateSharedLibrariesLPr(newPkg, null);
20712                            } catch (PackageManagerException e) {
20713                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20714                            }
20715                            updatePermissionsLPw(newPkg.packageName, newPkg,
20716                                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
20717                            mSettings.writeLPr();
20718                        }
20719                    } catch (PackageManagerException e) {
20720                        // Whoops! Something went wrong; try to roll back to the stub
20721                        Slog.w(TAG, "Failed to install compressed system package:"
20722                                + pkgSetting.name, e);
20723                        // Remove the failed install
20724                        removeCodePathLI(codePath);
20725
20726                        // Install the system package
20727                        try (PackageFreezer freezer =
20728                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20729                            synchronized (mPackages) {
20730                                // NOTE: The system package always needs to be enabled; even
20731                                // if it's for a compressed stub. If we don't, installing the
20732                                // system package fails during scan [scanning checks the disabled
20733                                // packages]. We will reverse this later, after we've "installed"
20734                                // the stub.
20735                                // This leaves us in a fragile state; the stub should never be
20736                                // enabled, so, cross your fingers and hope nothing goes wrong
20737                                // until we can disable the package later.
20738                                enableSystemPackageLPw(deletedPkg);
20739                            }
20740                            installPackageFromSystemLIF(new File(deletedPkg.codePath),
20741                                    false /*isPrivileged*/, null /*allUserHandles*/,
20742                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20743                                    true /*writeSettings*/);
20744                        } catch (PackageManagerException pme) {
20745                            Slog.w(TAG, "Failed to restore system package:"
20746                                    + deletedPkg.packageName, pme);
20747                        } finally {
20748                            synchronized (mPackages) {
20749                                mSettings.disableSystemPackageLPw(
20750                                        deletedPkg.packageName, true /*replaced*/);
20751                                mSettings.writeLPr();
20752                            }
20753                        }
20754                        return;
20755                    }
20756                    clearAppDataLIF(newPkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20757                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20758                    clearAppProfilesLIF(newPkg, UserHandle.USER_ALL);
20759                    mDexManager.notifyPackageUpdated(newPkg.packageName,
20760                            newPkg.baseCodePath, newPkg.splitCodePaths);
20761                }
20762            }
20763            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20764                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20765                // Don't care about who enables an app.
20766                callingPackage = null;
20767            }
20768            synchronized (mPackages) {
20769                pkgSetting.setEnabled(newState, userId, callingPackage);
20770            }
20771        } else {
20772            synchronized (mPackages) {
20773                // We're dealing with a component level state change
20774                // First, verify that this is a valid class name.
20775                PackageParser.Package pkg = pkgSetting.pkg;
20776                if (pkg == null || !pkg.hasComponentClassName(className)) {
20777                    if (pkg != null &&
20778                            pkg.applicationInfo.targetSdkVersion >=
20779                                    Build.VERSION_CODES.JELLY_BEAN) {
20780                        throw new IllegalArgumentException("Component class " + className
20781                                + " does not exist in " + packageName);
20782                    } else {
20783                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20784                                + className + " does not exist in " + packageName);
20785                    }
20786                }
20787                switch (newState) {
20788                    case COMPONENT_ENABLED_STATE_ENABLED:
20789                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20790                            return;
20791                        }
20792                        break;
20793                    case COMPONENT_ENABLED_STATE_DISABLED:
20794                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20795                            return;
20796                        }
20797                        break;
20798                    case COMPONENT_ENABLED_STATE_DEFAULT:
20799                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20800                            return;
20801                        }
20802                        break;
20803                    default:
20804                        Slog.e(TAG, "Invalid new component state: " + newState);
20805                        return;
20806                }
20807            }
20808        }
20809        synchronized (mPackages) {
20810            scheduleWritePackageRestrictionsLocked(userId);
20811            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20812            final long callingId = Binder.clearCallingIdentity();
20813            try {
20814                updateInstantAppInstallerLocked(packageName);
20815            } finally {
20816                Binder.restoreCallingIdentity(callingId);
20817            }
20818            components = mPendingBroadcasts.get(userId, packageName);
20819            final boolean newPackage = components == null;
20820            if (newPackage) {
20821                components = new ArrayList<String>();
20822            }
20823            if (!components.contains(componentName)) {
20824                components.add(componentName);
20825            }
20826            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20827                sendNow = true;
20828                // Purge entry from pending broadcast list if another one exists already
20829                // since we are sending one right away.
20830                mPendingBroadcasts.remove(userId, packageName);
20831            } else {
20832                if (newPackage) {
20833                    mPendingBroadcasts.put(userId, packageName, components);
20834                }
20835                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20836                    // Schedule a message
20837                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20838                }
20839            }
20840        }
20841
20842        long callingId = Binder.clearCallingIdentity();
20843        try {
20844            if (sendNow) {
20845                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20846                sendPackageChangedBroadcast(packageName,
20847                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20848            }
20849        } finally {
20850            Binder.restoreCallingIdentity(callingId);
20851        }
20852    }
20853
20854    @Override
20855    public void flushPackageRestrictionsAsUser(int userId) {
20856        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20857            return;
20858        }
20859        if (!sUserManager.exists(userId)) {
20860            return;
20861        }
20862        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20863                false /* checkShell */, "flushPackageRestrictions");
20864        synchronized (mPackages) {
20865            mSettings.writePackageRestrictionsLPr(userId);
20866            mDirtyUsers.remove(userId);
20867            if (mDirtyUsers.isEmpty()) {
20868                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20869            }
20870        }
20871    }
20872
20873    private void sendPackageChangedBroadcast(String packageName,
20874            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20875        if (DEBUG_INSTALL)
20876            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20877                    + componentNames);
20878        Bundle extras = new Bundle(4);
20879        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20880        String nameList[] = new String[componentNames.size()];
20881        componentNames.toArray(nameList);
20882        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20883        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20884        extras.putInt(Intent.EXTRA_UID, packageUid);
20885        // If this is not reporting a change of the overall package, then only send it
20886        // to registered receivers.  We don't want to launch a swath of apps for every
20887        // little component state change.
20888        final int flags = !componentNames.contains(packageName)
20889                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20890        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20891                new int[] {UserHandle.getUserId(packageUid)});
20892    }
20893
20894    @Override
20895    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20896        if (!sUserManager.exists(userId)) return;
20897        final int callingUid = Binder.getCallingUid();
20898        if (getInstantAppPackageName(callingUid) != null) {
20899            return;
20900        }
20901        final int permission = mContext.checkCallingOrSelfPermission(
20902                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20903        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20904        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20905                true /* requireFullPermission */, true /* checkShell */, "stop package");
20906        // writer
20907        synchronized (mPackages) {
20908            final PackageSetting ps = mSettings.mPackages.get(packageName);
20909            if (!filterAppAccessLPr(ps, callingUid, userId)
20910                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20911                            allowedByPermission, callingUid, userId)) {
20912                scheduleWritePackageRestrictionsLocked(userId);
20913            }
20914        }
20915    }
20916
20917    @Override
20918    public String getInstallerPackageName(String packageName) {
20919        final int callingUid = Binder.getCallingUid();
20920        if (getInstantAppPackageName(callingUid) != null) {
20921            return null;
20922        }
20923        // reader
20924        synchronized (mPackages) {
20925            final PackageSetting ps = mSettings.mPackages.get(packageName);
20926            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20927                return null;
20928            }
20929            return mSettings.getInstallerPackageNameLPr(packageName);
20930        }
20931    }
20932
20933    public boolean isOrphaned(String packageName) {
20934        // reader
20935        synchronized (mPackages) {
20936            return mSettings.isOrphaned(packageName);
20937        }
20938    }
20939
20940    @Override
20941    public int getApplicationEnabledSetting(String packageName, int userId) {
20942        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20943        int callingUid = Binder.getCallingUid();
20944        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20945                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20946        // reader
20947        synchronized (mPackages) {
20948            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20949                return COMPONENT_ENABLED_STATE_DISABLED;
20950            }
20951            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20952        }
20953    }
20954
20955    @Override
20956    public int getComponentEnabledSetting(ComponentName component, int userId) {
20957        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20958        int callingUid = Binder.getCallingUid();
20959        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20960                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20961        synchronized (mPackages) {
20962            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20963                    component, TYPE_UNKNOWN, userId)) {
20964                return COMPONENT_ENABLED_STATE_DISABLED;
20965            }
20966            return mSettings.getComponentEnabledSettingLPr(component, userId);
20967        }
20968    }
20969
20970    @Override
20971    public void enterSafeMode() {
20972        enforceSystemOrRoot("Only the system can request entering safe mode");
20973
20974        if (!mSystemReady) {
20975            mSafeMode = true;
20976        }
20977    }
20978
20979    @Override
20980    public void systemReady() {
20981        enforceSystemOrRoot("Only the system can claim the system is ready");
20982
20983        mSystemReady = true;
20984        final ContentResolver resolver = mContext.getContentResolver();
20985        ContentObserver co = new ContentObserver(mHandler) {
20986            @Override
20987            public void onChange(boolean selfChange) {
20988                mEphemeralAppsDisabled =
20989                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20990                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20991            }
20992        };
20993        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20994                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20995                false, co, UserHandle.USER_SYSTEM);
20996        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20997                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20998        co.onChange(true);
20999
21000        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21001        // disabled after already being started.
21002        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21003                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21004
21005        // Read the compatibilty setting when the system is ready.
21006        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21007                mContext.getContentResolver(),
21008                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21009        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21010        if (DEBUG_SETTINGS) {
21011            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21012        }
21013
21014        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21015
21016        synchronized (mPackages) {
21017            // Verify that all of the preferred activity components actually
21018            // exist.  It is possible for applications to be updated and at
21019            // that point remove a previously declared activity component that
21020            // had been set as a preferred activity.  We try to clean this up
21021            // the next time we encounter that preferred activity, but it is
21022            // possible for the user flow to never be able to return to that
21023            // situation so here we do a sanity check to make sure we haven't
21024            // left any junk around.
21025            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21026            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21027                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21028                removed.clear();
21029                for (PreferredActivity pa : pir.filterSet()) {
21030                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21031                        removed.add(pa);
21032                    }
21033                }
21034                if (removed.size() > 0) {
21035                    for (int r=0; r<removed.size(); r++) {
21036                        PreferredActivity pa = removed.get(r);
21037                        Slog.w(TAG, "Removing dangling preferred activity: "
21038                                + pa.mPref.mComponent);
21039                        pir.removeFilter(pa);
21040                    }
21041                    mSettings.writePackageRestrictionsLPr(
21042                            mSettings.mPreferredActivities.keyAt(i));
21043                }
21044            }
21045
21046            for (int userId : UserManagerService.getInstance().getUserIds()) {
21047                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21048                    grantPermissionsUserIds = ArrayUtils.appendInt(
21049                            grantPermissionsUserIds, userId);
21050                }
21051            }
21052        }
21053        sUserManager.systemReady();
21054
21055        synchronized(mPackages) {
21056            // If we upgraded grant all default permissions before kicking off.
21057            for (int userId : grantPermissionsUserIds) {
21058                mDefaultPermissionPolicy.grantDefaultPermissions(mPackages.values(), userId);
21059            }
21060        }
21061
21062        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21063            // If we did not grant default permissions, we preload from this the
21064            // default permission exceptions lazily to ensure we don't hit the
21065            // disk on a new user creation.
21066            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21067        }
21068
21069        // Now that we've scanned all packages, and granted any default
21070        // permissions, ensure permissions are updated. Beware of dragons if you
21071        // try optimizing this.
21072        synchronized (mPackages) {
21073            updatePermissionsLocked(null, null, StorageManager.UUID_PRIVATE_INTERNAL,
21074                    UPDATE_PERMISSIONS_ALL);
21075        }
21076
21077        // Kick off any messages waiting for system ready
21078        if (mPostSystemReadyMessages != null) {
21079            for (Message msg : mPostSystemReadyMessages) {
21080                msg.sendToTarget();
21081            }
21082            mPostSystemReadyMessages = null;
21083        }
21084
21085        // Watch for external volumes that come and go over time
21086        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21087        storage.registerListener(mStorageListener);
21088
21089        mInstallerService.systemReady();
21090        mPackageDexOptimizer.systemReady();
21091
21092        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21093                StorageManagerInternal.class);
21094        StorageManagerInternal.addExternalStoragePolicy(
21095                new StorageManagerInternal.ExternalStorageMountPolicy() {
21096            @Override
21097            public int getMountMode(int uid, String packageName) {
21098                if (Process.isIsolated(uid)) {
21099                    return Zygote.MOUNT_EXTERNAL_NONE;
21100                }
21101                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21102                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21103                }
21104                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21105                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21106                }
21107                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21108                    return Zygote.MOUNT_EXTERNAL_READ;
21109                }
21110                return Zygote.MOUNT_EXTERNAL_WRITE;
21111            }
21112
21113            @Override
21114            public boolean hasExternalStorage(int uid, String packageName) {
21115                return true;
21116            }
21117        });
21118
21119        // Now that we're mostly running, clean up stale users and apps
21120        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21121        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21122
21123        if (mPrivappPermissionsViolations != null) {
21124            Slog.wtf(TAG,"Signature|privileged permissions not in "
21125                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21126            mPrivappPermissionsViolations = null;
21127        }
21128    }
21129
21130    public void waitForAppDataPrepared() {
21131        if (mPrepareAppDataFuture == null) {
21132            return;
21133        }
21134        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21135        mPrepareAppDataFuture = null;
21136    }
21137
21138    @Override
21139    public boolean isSafeMode() {
21140        // allow instant applications
21141        return mSafeMode;
21142    }
21143
21144    @Override
21145    public boolean hasSystemUidErrors() {
21146        // allow instant applications
21147        return mHasSystemUidErrors;
21148    }
21149
21150    static String arrayToString(int[] array) {
21151        StringBuffer buf = new StringBuffer(128);
21152        buf.append('[');
21153        if (array != null) {
21154            for (int i=0; i<array.length; i++) {
21155                if (i > 0) buf.append(", ");
21156                buf.append(array[i]);
21157            }
21158        }
21159        buf.append(']');
21160        return buf.toString();
21161    }
21162
21163    @Override
21164    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21165            FileDescriptor err, String[] args, ShellCallback callback,
21166            ResultReceiver resultReceiver) {
21167        (new PackageManagerShellCommand(this)).exec(
21168                this, in, out, err, args, callback, resultReceiver);
21169    }
21170
21171    @Override
21172    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21173        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21174
21175        DumpState dumpState = new DumpState();
21176        boolean fullPreferred = false;
21177        boolean checkin = false;
21178
21179        String packageName = null;
21180        ArraySet<String> permissionNames = null;
21181
21182        int opti = 0;
21183        while (opti < args.length) {
21184            String opt = args[opti];
21185            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21186                break;
21187            }
21188            opti++;
21189
21190            if ("-a".equals(opt)) {
21191                // Right now we only know how to print all.
21192            } else if ("-h".equals(opt)) {
21193                pw.println("Package manager dump options:");
21194                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21195                pw.println("    --checkin: dump for a checkin");
21196                pw.println("    -f: print details of intent filters");
21197                pw.println("    -h: print this help");
21198                pw.println("  cmd may be one of:");
21199                pw.println("    l[ibraries]: list known shared libraries");
21200                pw.println("    f[eatures]: list device features");
21201                pw.println("    k[eysets]: print known keysets");
21202                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21203                pw.println("    perm[issions]: dump permissions");
21204                pw.println("    permission [name ...]: dump declaration and use of given permission");
21205                pw.println("    pref[erred]: print preferred package settings");
21206                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21207                pw.println("    prov[iders]: dump content providers");
21208                pw.println("    p[ackages]: dump installed packages");
21209                pw.println("    s[hared-users]: dump shared user IDs");
21210                pw.println("    m[essages]: print collected runtime messages");
21211                pw.println("    v[erifiers]: print package verifier info");
21212                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21213                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21214                pw.println("    version: print database version info");
21215                pw.println("    write: write current settings now");
21216                pw.println("    installs: details about install sessions");
21217                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21218                pw.println("    dexopt: dump dexopt state");
21219                pw.println("    compiler-stats: dump compiler statistics");
21220                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21221                pw.println("    <package.name>: info about given package");
21222                return;
21223            } else if ("--checkin".equals(opt)) {
21224                checkin = true;
21225            } else if ("-f".equals(opt)) {
21226                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21227            } else if ("--proto".equals(opt)) {
21228                dumpProto(fd);
21229                return;
21230            } else {
21231                pw.println("Unknown argument: " + opt + "; use -h for help");
21232            }
21233        }
21234
21235        // Is the caller requesting to dump a particular piece of data?
21236        if (opti < args.length) {
21237            String cmd = args[opti];
21238            opti++;
21239            // Is this a package name?
21240            if ("android".equals(cmd) || cmd.contains(".")) {
21241                packageName = cmd;
21242                // When dumping a single package, we always dump all of its
21243                // filter information since the amount of data will be reasonable.
21244                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21245            } else if ("check-permission".equals(cmd)) {
21246                if (opti >= args.length) {
21247                    pw.println("Error: check-permission missing permission argument");
21248                    return;
21249                }
21250                String perm = args[opti];
21251                opti++;
21252                if (opti >= args.length) {
21253                    pw.println("Error: check-permission missing package argument");
21254                    return;
21255                }
21256
21257                String pkg = args[opti];
21258                opti++;
21259                int user = UserHandle.getUserId(Binder.getCallingUid());
21260                if (opti < args.length) {
21261                    try {
21262                        user = Integer.parseInt(args[opti]);
21263                    } catch (NumberFormatException e) {
21264                        pw.println("Error: check-permission user argument is not a number: "
21265                                + args[opti]);
21266                        return;
21267                    }
21268                }
21269
21270                // Normalize package name to handle renamed packages and static libs
21271                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21272
21273                pw.println(checkPermission(perm, pkg, user));
21274                return;
21275            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21276                dumpState.setDump(DumpState.DUMP_LIBS);
21277            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21278                dumpState.setDump(DumpState.DUMP_FEATURES);
21279            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21280                if (opti >= args.length) {
21281                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21282                            | DumpState.DUMP_SERVICE_RESOLVERS
21283                            | DumpState.DUMP_RECEIVER_RESOLVERS
21284                            | DumpState.DUMP_CONTENT_RESOLVERS);
21285                } else {
21286                    while (opti < args.length) {
21287                        String name = args[opti];
21288                        if ("a".equals(name) || "activity".equals(name)) {
21289                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21290                        } else if ("s".equals(name) || "service".equals(name)) {
21291                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21292                        } else if ("r".equals(name) || "receiver".equals(name)) {
21293                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21294                        } else if ("c".equals(name) || "content".equals(name)) {
21295                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21296                        } else {
21297                            pw.println("Error: unknown resolver table type: " + name);
21298                            return;
21299                        }
21300                        opti++;
21301                    }
21302                }
21303            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21304                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21305            } else if ("permission".equals(cmd)) {
21306                if (opti >= args.length) {
21307                    pw.println("Error: permission requires permission name");
21308                    return;
21309                }
21310                permissionNames = new ArraySet<>();
21311                while (opti < args.length) {
21312                    permissionNames.add(args[opti]);
21313                    opti++;
21314                }
21315                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21316                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21317            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21318                dumpState.setDump(DumpState.DUMP_PREFERRED);
21319            } else if ("preferred-xml".equals(cmd)) {
21320                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21321                if (opti < args.length && "--full".equals(args[opti])) {
21322                    fullPreferred = true;
21323                    opti++;
21324                }
21325            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21326                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21327            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21328                dumpState.setDump(DumpState.DUMP_PACKAGES);
21329            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21330                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21331            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21332                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21333            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21334                dumpState.setDump(DumpState.DUMP_MESSAGES);
21335            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21336                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21337            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21338                    || "intent-filter-verifiers".equals(cmd)) {
21339                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21340            } else if ("version".equals(cmd)) {
21341                dumpState.setDump(DumpState.DUMP_VERSION);
21342            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21343                dumpState.setDump(DumpState.DUMP_KEYSETS);
21344            } else if ("installs".equals(cmd)) {
21345                dumpState.setDump(DumpState.DUMP_INSTALLS);
21346            } else if ("frozen".equals(cmd)) {
21347                dumpState.setDump(DumpState.DUMP_FROZEN);
21348            } else if ("volumes".equals(cmd)) {
21349                dumpState.setDump(DumpState.DUMP_VOLUMES);
21350            } else if ("dexopt".equals(cmd)) {
21351                dumpState.setDump(DumpState.DUMP_DEXOPT);
21352            } else if ("compiler-stats".equals(cmd)) {
21353                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21354            } else if ("changes".equals(cmd)) {
21355                dumpState.setDump(DumpState.DUMP_CHANGES);
21356            } else if ("write".equals(cmd)) {
21357                synchronized (mPackages) {
21358                    mSettings.writeLPr();
21359                    pw.println("Settings written.");
21360                    return;
21361                }
21362            }
21363        }
21364
21365        if (checkin) {
21366            pw.println("vers,1");
21367        }
21368
21369        // reader
21370        synchronized (mPackages) {
21371            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21372                if (!checkin) {
21373                    if (dumpState.onTitlePrinted())
21374                        pw.println();
21375                    pw.println("Database versions:");
21376                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21377                }
21378            }
21379
21380            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21381                if (!checkin) {
21382                    if (dumpState.onTitlePrinted())
21383                        pw.println();
21384                    pw.println("Verifiers:");
21385                    pw.print("  Required: ");
21386                    pw.print(mRequiredVerifierPackage);
21387                    pw.print(" (uid=");
21388                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21389                            UserHandle.USER_SYSTEM));
21390                    pw.println(")");
21391                } else if (mRequiredVerifierPackage != null) {
21392                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21393                    pw.print(",");
21394                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21395                            UserHandle.USER_SYSTEM));
21396                }
21397            }
21398
21399            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21400                    packageName == null) {
21401                if (mIntentFilterVerifierComponent != null) {
21402                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21403                    if (!checkin) {
21404                        if (dumpState.onTitlePrinted())
21405                            pw.println();
21406                        pw.println("Intent Filter Verifier:");
21407                        pw.print("  Using: ");
21408                        pw.print(verifierPackageName);
21409                        pw.print(" (uid=");
21410                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21411                                UserHandle.USER_SYSTEM));
21412                        pw.println(")");
21413                    } else if (verifierPackageName != null) {
21414                        pw.print("ifv,"); pw.print(verifierPackageName);
21415                        pw.print(",");
21416                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21417                                UserHandle.USER_SYSTEM));
21418                    }
21419                } else {
21420                    pw.println();
21421                    pw.println("No Intent Filter Verifier available!");
21422                }
21423            }
21424
21425            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21426                boolean printedHeader = false;
21427                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21428                while (it.hasNext()) {
21429                    String libName = it.next();
21430                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21431                    if (versionedLib == null) {
21432                        continue;
21433                    }
21434                    final int versionCount = versionedLib.size();
21435                    for (int i = 0; i < versionCount; i++) {
21436                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21437                        if (!checkin) {
21438                            if (!printedHeader) {
21439                                if (dumpState.onTitlePrinted())
21440                                    pw.println();
21441                                pw.println("Libraries:");
21442                                printedHeader = true;
21443                            }
21444                            pw.print("  ");
21445                        } else {
21446                            pw.print("lib,");
21447                        }
21448                        pw.print(libEntry.info.getName());
21449                        if (libEntry.info.isStatic()) {
21450                            pw.print(" version=" + libEntry.info.getVersion());
21451                        }
21452                        if (!checkin) {
21453                            pw.print(" -> ");
21454                        }
21455                        if (libEntry.path != null) {
21456                            pw.print(" (jar) ");
21457                            pw.print(libEntry.path);
21458                        } else {
21459                            pw.print(" (apk) ");
21460                            pw.print(libEntry.apk);
21461                        }
21462                        pw.println();
21463                    }
21464                }
21465            }
21466
21467            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21468                if (dumpState.onTitlePrinted())
21469                    pw.println();
21470                if (!checkin) {
21471                    pw.println("Features:");
21472                }
21473
21474                synchronized (mAvailableFeatures) {
21475                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21476                        if (checkin) {
21477                            pw.print("feat,");
21478                            pw.print(feat.name);
21479                            pw.print(",");
21480                            pw.println(feat.version);
21481                        } else {
21482                            pw.print("  ");
21483                            pw.print(feat.name);
21484                            if (feat.version > 0) {
21485                                pw.print(" version=");
21486                                pw.print(feat.version);
21487                            }
21488                            pw.println();
21489                        }
21490                    }
21491                }
21492            }
21493
21494            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21495                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21496                        : "Activity Resolver Table:", "  ", packageName,
21497                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21498                    dumpState.setTitlePrinted(true);
21499                }
21500            }
21501            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21502                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21503                        : "Receiver Resolver Table:", "  ", packageName,
21504                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21505                    dumpState.setTitlePrinted(true);
21506                }
21507            }
21508            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21509                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21510                        : "Service Resolver Table:", "  ", packageName,
21511                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21512                    dumpState.setTitlePrinted(true);
21513                }
21514            }
21515            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21516                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21517                        : "Provider Resolver Table:", "  ", packageName,
21518                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21519                    dumpState.setTitlePrinted(true);
21520                }
21521            }
21522
21523            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21524                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21525                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21526                    int user = mSettings.mPreferredActivities.keyAt(i);
21527                    if (pir.dump(pw,
21528                            dumpState.getTitlePrinted()
21529                                ? "\nPreferred Activities User " + user + ":"
21530                                : "Preferred Activities User " + user + ":", "  ",
21531                            packageName, true, false)) {
21532                        dumpState.setTitlePrinted(true);
21533                    }
21534                }
21535            }
21536
21537            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21538                pw.flush();
21539                FileOutputStream fout = new FileOutputStream(fd);
21540                BufferedOutputStream str = new BufferedOutputStream(fout);
21541                XmlSerializer serializer = new FastXmlSerializer();
21542                try {
21543                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21544                    serializer.startDocument(null, true);
21545                    serializer.setFeature(
21546                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21547                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21548                    serializer.endDocument();
21549                    serializer.flush();
21550                } catch (IllegalArgumentException e) {
21551                    pw.println("Failed writing: " + e);
21552                } catch (IllegalStateException e) {
21553                    pw.println("Failed writing: " + e);
21554                } catch (IOException e) {
21555                    pw.println("Failed writing: " + e);
21556                }
21557            }
21558
21559            if (!checkin
21560                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21561                    && packageName == null) {
21562                pw.println();
21563                int count = mSettings.mPackages.size();
21564                if (count == 0) {
21565                    pw.println("No applications!");
21566                    pw.println();
21567                } else {
21568                    final String prefix = "  ";
21569                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21570                    if (allPackageSettings.size() == 0) {
21571                        pw.println("No domain preferred apps!");
21572                        pw.println();
21573                    } else {
21574                        pw.println("App verification status:");
21575                        pw.println();
21576                        count = 0;
21577                        for (PackageSetting ps : allPackageSettings) {
21578                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21579                            if (ivi == null || ivi.getPackageName() == null) continue;
21580                            pw.println(prefix + "Package: " + ivi.getPackageName());
21581                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21582                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21583                            pw.println();
21584                            count++;
21585                        }
21586                        if (count == 0) {
21587                            pw.println(prefix + "No app verification established.");
21588                            pw.println();
21589                        }
21590                        for (int userId : sUserManager.getUserIds()) {
21591                            pw.println("App linkages for user " + userId + ":");
21592                            pw.println();
21593                            count = 0;
21594                            for (PackageSetting ps : allPackageSettings) {
21595                                final long status = ps.getDomainVerificationStatusForUser(userId);
21596                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21597                                        && !DEBUG_DOMAIN_VERIFICATION) {
21598                                    continue;
21599                                }
21600                                pw.println(prefix + "Package: " + ps.name);
21601                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21602                                String statusStr = IntentFilterVerificationInfo.
21603                                        getStatusStringFromValue(status);
21604                                pw.println(prefix + "Status:  " + statusStr);
21605                                pw.println();
21606                                count++;
21607                            }
21608                            if (count == 0) {
21609                                pw.println(prefix + "No configured app linkages.");
21610                                pw.println();
21611                            }
21612                        }
21613                    }
21614                }
21615            }
21616
21617            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21618                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21619            }
21620
21621            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21622                boolean printedSomething = false;
21623                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21624                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21625                        continue;
21626                    }
21627                    if (!printedSomething) {
21628                        if (dumpState.onTitlePrinted())
21629                            pw.println();
21630                        pw.println("Registered ContentProviders:");
21631                        printedSomething = true;
21632                    }
21633                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21634                    pw.print("    "); pw.println(p.toString());
21635                }
21636                printedSomething = false;
21637                for (Map.Entry<String, PackageParser.Provider> entry :
21638                        mProvidersByAuthority.entrySet()) {
21639                    PackageParser.Provider p = entry.getValue();
21640                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21641                        continue;
21642                    }
21643                    if (!printedSomething) {
21644                        if (dumpState.onTitlePrinted())
21645                            pw.println();
21646                        pw.println("ContentProvider Authorities:");
21647                        printedSomething = true;
21648                    }
21649                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21650                    pw.print("    "); pw.println(p.toString());
21651                    if (p.info != null && p.info.applicationInfo != null) {
21652                        final String appInfo = p.info.applicationInfo.toString();
21653                        pw.print("      applicationInfo="); pw.println(appInfo);
21654                    }
21655                }
21656            }
21657
21658            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21659                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21660            }
21661
21662            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21663                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21664            }
21665
21666            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21667                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21668            }
21669
21670            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21671                if (dumpState.onTitlePrinted()) pw.println();
21672                pw.println("Package Changes:");
21673                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21674                final int K = mChangedPackages.size();
21675                for (int i = 0; i < K; i++) {
21676                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21677                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21678                    final int N = changes.size();
21679                    if (N == 0) {
21680                        pw.print("    "); pw.println("No packages changed");
21681                    } else {
21682                        for (int j = 0; j < N; j++) {
21683                            final String pkgName = changes.valueAt(j);
21684                            final int sequenceNumber = changes.keyAt(j);
21685                            pw.print("    ");
21686                            pw.print("seq=");
21687                            pw.print(sequenceNumber);
21688                            pw.print(", package=");
21689                            pw.println(pkgName);
21690                        }
21691                    }
21692                }
21693            }
21694
21695            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21696                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21697            }
21698
21699            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21700                // XXX should handle packageName != null by dumping only install data that
21701                // the given package is involved with.
21702                if (dumpState.onTitlePrinted()) pw.println();
21703
21704                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21705                ipw.println();
21706                ipw.println("Frozen packages:");
21707                ipw.increaseIndent();
21708                if (mFrozenPackages.size() == 0) {
21709                    ipw.println("(none)");
21710                } else {
21711                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21712                        ipw.println(mFrozenPackages.valueAt(i));
21713                    }
21714                }
21715                ipw.decreaseIndent();
21716            }
21717
21718            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21719                if (dumpState.onTitlePrinted()) pw.println();
21720
21721                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21722                ipw.println();
21723                ipw.println("Loaded volumes:");
21724                ipw.increaseIndent();
21725                if (mLoadedVolumes.size() == 0) {
21726                    ipw.println("(none)");
21727                } else {
21728                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
21729                        ipw.println(mLoadedVolumes.valueAt(i));
21730                    }
21731                }
21732                ipw.decreaseIndent();
21733            }
21734
21735            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21736                if (dumpState.onTitlePrinted()) pw.println();
21737                dumpDexoptStateLPr(pw, packageName);
21738            }
21739
21740            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21741                if (dumpState.onTitlePrinted()) pw.println();
21742                dumpCompilerStatsLPr(pw, packageName);
21743            }
21744
21745            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21746                if (dumpState.onTitlePrinted()) pw.println();
21747                mSettings.dumpReadMessagesLPr(pw, dumpState);
21748
21749                pw.println();
21750                pw.println("Package warning messages:");
21751                BufferedReader in = null;
21752                String line = null;
21753                try {
21754                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21755                    while ((line = in.readLine()) != null) {
21756                        if (line.contains("ignored: updated version")) continue;
21757                        pw.println(line);
21758                    }
21759                } catch (IOException ignored) {
21760                } finally {
21761                    IoUtils.closeQuietly(in);
21762                }
21763            }
21764
21765            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21766                BufferedReader in = null;
21767                String line = null;
21768                try {
21769                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21770                    while ((line = in.readLine()) != null) {
21771                        if (line.contains("ignored: updated version")) continue;
21772                        pw.print("msg,");
21773                        pw.println(line);
21774                    }
21775                } catch (IOException ignored) {
21776                } finally {
21777                    IoUtils.closeQuietly(in);
21778                }
21779            }
21780        }
21781
21782        // PackageInstaller should be called outside of mPackages lock
21783        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21784            // XXX should handle packageName != null by dumping only install data that
21785            // the given package is involved with.
21786            if (dumpState.onTitlePrinted()) pw.println();
21787            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21788        }
21789    }
21790
21791    private void dumpProto(FileDescriptor fd) {
21792        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21793
21794        synchronized (mPackages) {
21795            final long requiredVerifierPackageToken =
21796                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21797            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21798            proto.write(
21799                    PackageServiceDumpProto.PackageShortProto.UID,
21800                    getPackageUid(
21801                            mRequiredVerifierPackage,
21802                            MATCH_DEBUG_TRIAGED_MISSING,
21803                            UserHandle.USER_SYSTEM));
21804            proto.end(requiredVerifierPackageToken);
21805
21806            if (mIntentFilterVerifierComponent != null) {
21807                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21808                final long verifierPackageToken =
21809                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21810                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21811                proto.write(
21812                        PackageServiceDumpProto.PackageShortProto.UID,
21813                        getPackageUid(
21814                                verifierPackageName,
21815                                MATCH_DEBUG_TRIAGED_MISSING,
21816                                UserHandle.USER_SYSTEM));
21817                proto.end(verifierPackageToken);
21818            }
21819
21820            dumpSharedLibrariesProto(proto);
21821            dumpFeaturesProto(proto);
21822            mSettings.dumpPackagesProto(proto);
21823            mSettings.dumpSharedUsersProto(proto);
21824            dumpMessagesProto(proto);
21825        }
21826        proto.flush();
21827    }
21828
21829    private void dumpMessagesProto(ProtoOutputStream proto) {
21830        BufferedReader in = null;
21831        String line = null;
21832        try {
21833            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21834            while ((line = in.readLine()) != null) {
21835                if (line.contains("ignored: updated version")) continue;
21836                proto.write(PackageServiceDumpProto.MESSAGES, line);
21837            }
21838        } catch (IOException ignored) {
21839        } finally {
21840            IoUtils.closeQuietly(in);
21841        }
21842    }
21843
21844    private void dumpFeaturesProto(ProtoOutputStream proto) {
21845        synchronized (mAvailableFeatures) {
21846            final int count = mAvailableFeatures.size();
21847            for (int i = 0; i < count; i++) {
21848                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
21849                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
21850                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
21851                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
21852                proto.end(featureToken);
21853            }
21854        }
21855    }
21856
21857    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21858        final int count = mSharedLibraries.size();
21859        for (int i = 0; i < count; i++) {
21860            final String libName = mSharedLibraries.keyAt(i);
21861            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21862            if (versionedLib == null) {
21863                continue;
21864            }
21865            final int versionCount = versionedLib.size();
21866            for (int j = 0; j < versionCount; j++) {
21867                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21868                final long sharedLibraryToken =
21869                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21870                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21871                final boolean isJar = (libEntry.path != null);
21872                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21873                if (isJar) {
21874                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21875                } else {
21876                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21877                }
21878                proto.end(sharedLibraryToken);
21879            }
21880        }
21881    }
21882
21883    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21884        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21885        ipw.println();
21886        ipw.println("Dexopt state:");
21887        ipw.increaseIndent();
21888        Collection<PackageParser.Package> packages = null;
21889        if (packageName != null) {
21890            PackageParser.Package targetPackage = mPackages.get(packageName);
21891            if (targetPackage != null) {
21892                packages = Collections.singletonList(targetPackage);
21893            } else {
21894                ipw.println("Unable to find package: " + packageName);
21895                return;
21896            }
21897        } else {
21898            packages = mPackages.values();
21899        }
21900
21901        for (PackageParser.Package pkg : packages) {
21902            ipw.println("[" + pkg.packageName + "]");
21903            ipw.increaseIndent();
21904            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21905                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21906            ipw.decreaseIndent();
21907        }
21908    }
21909
21910    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21911        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21912        ipw.println();
21913        ipw.println("Compiler stats:");
21914        ipw.increaseIndent();
21915        Collection<PackageParser.Package> packages = null;
21916        if (packageName != null) {
21917            PackageParser.Package targetPackage = mPackages.get(packageName);
21918            if (targetPackage != null) {
21919                packages = Collections.singletonList(targetPackage);
21920            } else {
21921                ipw.println("Unable to find package: " + packageName);
21922                return;
21923            }
21924        } else {
21925            packages = mPackages.values();
21926        }
21927
21928        for (PackageParser.Package pkg : packages) {
21929            ipw.println("[" + pkg.packageName + "]");
21930            ipw.increaseIndent();
21931
21932            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21933            if (stats == null) {
21934                ipw.println("(No recorded stats)");
21935            } else {
21936                stats.dump(ipw);
21937            }
21938            ipw.decreaseIndent();
21939        }
21940    }
21941
21942    private String dumpDomainString(String packageName) {
21943        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21944                .getList();
21945        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21946
21947        ArraySet<String> result = new ArraySet<>();
21948        if (iviList.size() > 0) {
21949            for (IntentFilterVerificationInfo ivi : iviList) {
21950                for (String host : ivi.getDomains()) {
21951                    result.add(host);
21952                }
21953            }
21954        }
21955        if (filters != null && filters.size() > 0) {
21956            for (IntentFilter filter : filters) {
21957                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21958                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21959                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21960                    result.addAll(filter.getHostsList());
21961                }
21962            }
21963        }
21964
21965        StringBuilder sb = new StringBuilder(result.size() * 16);
21966        for (String domain : result) {
21967            if (sb.length() > 0) sb.append(" ");
21968            sb.append(domain);
21969        }
21970        return sb.toString();
21971    }
21972
21973    // ------- apps on sdcard specific code -------
21974    static final boolean DEBUG_SD_INSTALL = false;
21975
21976    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21977
21978    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21979
21980    private boolean mMediaMounted = false;
21981
21982    static String getEncryptKey() {
21983        try {
21984            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21985                    SD_ENCRYPTION_KEYSTORE_NAME);
21986            if (sdEncKey == null) {
21987                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21988                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21989                if (sdEncKey == null) {
21990                    Slog.e(TAG, "Failed to create encryption keys");
21991                    return null;
21992                }
21993            }
21994            return sdEncKey;
21995        } catch (NoSuchAlgorithmException nsae) {
21996            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21997            return null;
21998        } catch (IOException ioe) {
21999            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22000            return null;
22001        }
22002    }
22003
22004    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22005            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22006        final int size = infos.size();
22007        final String[] packageNames = new String[size];
22008        final int[] packageUids = new int[size];
22009        for (int i = 0; i < size; i++) {
22010            final ApplicationInfo info = infos.get(i);
22011            packageNames[i] = info.packageName;
22012            packageUids[i] = info.uid;
22013        }
22014        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22015                finishedReceiver);
22016    }
22017
22018    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22019            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22020        sendResourcesChangedBroadcast(mediaStatus, replacing,
22021                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22022    }
22023
22024    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22025            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22026        int size = pkgList.length;
22027        if (size > 0) {
22028            // Send broadcasts here
22029            Bundle extras = new Bundle();
22030            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22031            if (uidArr != null) {
22032                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22033            }
22034            if (replacing) {
22035                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22036            }
22037            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22038                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22039            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
22040        }
22041    }
22042
22043    private void loadPrivatePackages(final VolumeInfo vol) {
22044        mHandler.post(new Runnable() {
22045            @Override
22046            public void run() {
22047                loadPrivatePackagesInner(vol);
22048            }
22049        });
22050    }
22051
22052    private void loadPrivatePackagesInner(VolumeInfo vol) {
22053        final String volumeUuid = vol.fsUuid;
22054        if (TextUtils.isEmpty(volumeUuid)) {
22055            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22056            return;
22057        }
22058
22059        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22060        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22061        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22062
22063        final VersionInfo ver;
22064        final List<PackageSetting> packages;
22065        synchronized (mPackages) {
22066            ver = mSettings.findOrCreateVersion(volumeUuid);
22067            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22068        }
22069
22070        for (PackageSetting ps : packages) {
22071            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22072            synchronized (mInstallLock) {
22073                final PackageParser.Package pkg;
22074                try {
22075                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22076                    loaded.add(pkg.applicationInfo);
22077
22078                } catch (PackageManagerException e) {
22079                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22080                }
22081
22082                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22083                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22084                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22085                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22086                }
22087            }
22088        }
22089
22090        // Reconcile app data for all started/unlocked users
22091        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22092        final UserManager um = mContext.getSystemService(UserManager.class);
22093        UserManagerInternal umInternal = getUserManagerInternal();
22094        for (UserInfo user : um.getUsers()) {
22095            final int flags;
22096            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22097                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22098            } else if (umInternal.isUserRunning(user.id)) {
22099                flags = StorageManager.FLAG_STORAGE_DE;
22100            } else {
22101                continue;
22102            }
22103
22104            try {
22105                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22106                synchronized (mInstallLock) {
22107                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22108                }
22109            } catch (IllegalStateException e) {
22110                // Device was probably ejected, and we'll process that event momentarily
22111                Slog.w(TAG, "Failed to prepare storage: " + e);
22112            }
22113        }
22114
22115        synchronized (mPackages) {
22116            int updateFlags = UPDATE_PERMISSIONS_ALL;
22117            if (ver.sdkVersion != mSdkVersion) {
22118                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22119                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22120                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22121            }
22122            updatePermissionsLocked(null, null, volumeUuid, updateFlags);
22123
22124            // Yay, everything is now upgraded
22125            ver.forceCurrent();
22126
22127            mSettings.writeLPr();
22128        }
22129
22130        for (PackageFreezer freezer : freezers) {
22131            freezer.close();
22132        }
22133
22134        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22135        sendResourcesChangedBroadcast(true, false, loaded, null);
22136        mLoadedVolumes.add(vol.getId());
22137    }
22138
22139    private void unloadPrivatePackages(final VolumeInfo vol) {
22140        mHandler.post(new Runnable() {
22141            @Override
22142            public void run() {
22143                unloadPrivatePackagesInner(vol);
22144            }
22145        });
22146    }
22147
22148    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22149        final String volumeUuid = vol.fsUuid;
22150        if (TextUtils.isEmpty(volumeUuid)) {
22151            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22152            return;
22153        }
22154
22155        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22156        synchronized (mInstallLock) {
22157        synchronized (mPackages) {
22158            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22159            for (PackageSetting ps : packages) {
22160                if (ps.pkg == null) continue;
22161
22162                final ApplicationInfo info = ps.pkg.applicationInfo;
22163                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22164                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22165
22166                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22167                        "unloadPrivatePackagesInner")) {
22168                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22169                            false, null)) {
22170                        unloaded.add(info);
22171                    } else {
22172                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22173                    }
22174                }
22175
22176                // Try very hard to release any references to this package
22177                // so we don't risk the system server being killed due to
22178                // open FDs
22179                AttributeCache.instance().removePackage(ps.name);
22180            }
22181
22182            mSettings.writeLPr();
22183        }
22184        }
22185
22186        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22187        sendResourcesChangedBroadcast(false, false, unloaded, null);
22188        mLoadedVolumes.remove(vol.getId());
22189
22190        // Try very hard to release any references to this path so we don't risk
22191        // the system server being killed due to open FDs
22192        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
22193
22194        for (int i = 0; i < 3; i++) {
22195            System.gc();
22196            System.runFinalization();
22197        }
22198    }
22199
22200    private void assertPackageKnown(String volumeUuid, String packageName)
22201            throws PackageManagerException {
22202        synchronized (mPackages) {
22203            // Normalize package name to handle renamed packages
22204            packageName = normalizePackageNameLPr(packageName);
22205
22206            final PackageSetting ps = mSettings.mPackages.get(packageName);
22207            if (ps == null) {
22208                throw new PackageManagerException("Package " + packageName + " is unknown");
22209            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22210                throw new PackageManagerException(
22211                        "Package " + packageName + " found on unknown volume " + volumeUuid
22212                                + "; expected volume " + ps.volumeUuid);
22213            }
22214        }
22215    }
22216
22217    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22218            throws PackageManagerException {
22219        synchronized (mPackages) {
22220            // Normalize package name to handle renamed packages
22221            packageName = normalizePackageNameLPr(packageName);
22222
22223            final PackageSetting ps = mSettings.mPackages.get(packageName);
22224            if (ps == null) {
22225                throw new PackageManagerException("Package " + packageName + " is unknown");
22226            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22227                throw new PackageManagerException(
22228                        "Package " + packageName + " found on unknown volume " + volumeUuid
22229                                + "; expected volume " + ps.volumeUuid);
22230            } else if (!ps.getInstalled(userId)) {
22231                throw new PackageManagerException(
22232                        "Package " + packageName + " not installed for user " + userId);
22233            }
22234        }
22235    }
22236
22237    private List<String> collectAbsoluteCodePaths() {
22238        synchronized (mPackages) {
22239            List<String> codePaths = new ArrayList<>();
22240            final int packageCount = mSettings.mPackages.size();
22241            for (int i = 0; i < packageCount; i++) {
22242                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22243                codePaths.add(ps.codePath.getAbsolutePath());
22244            }
22245            return codePaths;
22246        }
22247    }
22248
22249    /**
22250     * Examine all apps present on given mounted volume, and destroy apps that
22251     * aren't expected, either due to uninstallation or reinstallation on
22252     * another volume.
22253     */
22254    private void reconcileApps(String volumeUuid) {
22255        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22256        List<File> filesToDelete = null;
22257
22258        final File[] files = FileUtils.listFilesOrEmpty(
22259                Environment.getDataAppDirectory(volumeUuid));
22260        for (File file : files) {
22261            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22262                    && !PackageInstallerService.isStageName(file.getName());
22263            if (!isPackage) {
22264                // Ignore entries which are not packages
22265                continue;
22266            }
22267
22268            String absolutePath = file.getAbsolutePath();
22269
22270            boolean pathValid = false;
22271            final int absoluteCodePathCount = absoluteCodePaths.size();
22272            for (int i = 0; i < absoluteCodePathCount; i++) {
22273                String absoluteCodePath = absoluteCodePaths.get(i);
22274                if (absolutePath.startsWith(absoluteCodePath)) {
22275                    pathValid = true;
22276                    break;
22277                }
22278            }
22279
22280            if (!pathValid) {
22281                if (filesToDelete == null) {
22282                    filesToDelete = new ArrayList<>();
22283                }
22284                filesToDelete.add(file);
22285            }
22286        }
22287
22288        if (filesToDelete != null) {
22289            final int fileToDeleteCount = filesToDelete.size();
22290            for (int i = 0; i < fileToDeleteCount; i++) {
22291                File fileToDelete = filesToDelete.get(i);
22292                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22293                synchronized (mInstallLock) {
22294                    removeCodePathLI(fileToDelete);
22295                }
22296            }
22297        }
22298    }
22299
22300    /**
22301     * Reconcile all app data for the given user.
22302     * <p>
22303     * Verifies that directories exist and that ownership and labeling is
22304     * correct for all installed apps on all mounted volumes.
22305     */
22306    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22307        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22308        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22309            final String volumeUuid = vol.getFsUuid();
22310            synchronized (mInstallLock) {
22311                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22312            }
22313        }
22314    }
22315
22316    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22317            boolean migrateAppData) {
22318        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22319    }
22320
22321    /**
22322     * Reconcile all app data on given mounted volume.
22323     * <p>
22324     * Destroys app data that isn't expected, either due to uninstallation or
22325     * reinstallation on another volume.
22326     * <p>
22327     * Verifies that directories exist and that ownership and labeling is
22328     * correct for all installed apps.
22329     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22330     */
22331    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22332            boolean migrateAppData, boolean onlyCoreApps) {
22333        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22334                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22335        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22336
22337        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22338        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22339
22340        // First look for stale data that doesn't belong, and check if things
22341        // have changed since we did our last restorecon
22342        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22343            if (StorageManager.isFileEncryptedNativeOrEmulated()
22344                    && !StorageManager.isUserKeyUnlocked(userId)) {
22345                throw new RuntimeException(
22346                        "Yikes, someone asked us to reconcile CE storage while " + userId
22347                                + " was still locked; this would have caused massive data loss!");
22348            }
22349
22350            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22351            for (File file : files) {
22352                final String packageName = file.getName();
22353                try {
22354                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22355                } catch (PackageManagerException e) {
22356                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22357                    try {
22358                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22359                                StorageManager.FLAG_STORAGE_CE, 0);
22360                    } catch (InstallerException e2) {
22361                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22362                    }
22363                }
22364            }
22365        }
22366        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22367            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22368            for (File file : files) {
22369                final String packageName = file.getName();
22370                try {
22371                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22372                } catch (PackageManagerException e) {
22373                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22374                    try {
22375                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22376                                StorageManager.FLAG_STORAGE_DE, 0);
22377                    } catch (InstallerException e2) {
22378                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22379                    }
22380                }
22381            }
22382        }
22383
22384        // Ensure that data directories are ready to roll for all packages
22385        // installed for this volume and user
22386        final List<PackageSetting> packages;
22387        synchronized (mPackages) {
22388            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22389        }
22390        int preparedCount = 0;
22391        for (PackageSetting ps : packages) {
22392            final String packageName = ps.name;
22393            if (ps.pkg == null) {
22394                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22395                // TODO: might be due to legacy ASEC apps; we should circle back
22396                // and reconcile again once they're scanned
22397                continue;
22398            }
22399            // Skip non-core apps if requested
22400            if (onlyCoreApps && !ps.pkg.coreApp) {
22401                result.add(packageName);
22402                continue;
22403            }
22404
22405            if (ps.getInstalled(userId)) {
22406                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22407                preparedCount++;
22408            }
22409        }
22410
22411        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22412        return result;
22413    }
22414
22415    /**
22416     * Prepare app data for the given app just after it was installed or
22417     * upgraded. This method carefully only touches users that it's installed
22418     * for, and it forces a restorecon to handle any seinfo changes.
22419     * <p>
22420     * Verifies that directories exist and that ownership and labeling is
22421     * correct for all installed apps. If there is an ownership mismatch, it
22422     * will try recovering system apps by wiping data; third-party app data is
22423     * left intact.
22424     * <p>
22425     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22426     */
22427    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22428        final PackageSetting ps;
22429        synchronized (mPackages) {
22430            ps = mSettings.mPackages.get(pkg.packageName);
22431            mSettings.writeKernelMappingLPr(ps);
22432        }
22433
22434        final UserManager um = mContext.getSystemService(UserManager.class);
22435        UserManagerInternal umInternal = getUserManagerInternal();
22436        for (UserInfo user : um.getUsers()) {
22437            final int flags;
22438            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22439                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22440            } else if (umInternal.isUserRunning(user.id)) {
22441                flags = StorageManager.FLAG_STORAGE_DE;
22442            } else {
22443                continue;
22444            }
22445
22446            if (ps.getInstalled(user.id)) {
22447                // TODO: when user data is locked, mark that we're still dirty
22448                prepareAppDataLIF(pkg, user.id, flags);
22449            }
22450        }
22451    }
22452
22453    /**
22454     * Prepare app data for the given app.
22455     * <p>
22456     * Verifies that directories exist and that ownership and labeling is
22457     * correct for all installed apps. If there is an ownership mismatch, this
22458     * will try recovering system apps by wiping data; third-party app data is
22459     * left intact.
22460     */
22461    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22462        if (pkg == null) {
22463            Slog.wtf(TAG, "Package was null!", new Throwable());
22464            return;
22465        }
22466        prepareAppDataLeafLIF(pkg, userId, flags);
22467        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22468        for (int i = 0; i < childCount; i++) {
22469            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22470        }
22471    }
22472
22473    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22474            boolean maybeMigrateAppData) {
22475        prepareAppDataLIF(pkg, userId, flags);
22476
22477        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22478            // We may have just shuffled around app data directories, so
22479            // prepare them one more time
22480            prepareAppDataLIF(pkg, userId, flags);
22481        }
22482    }
22483
22484    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22485        if (DEBUG_APP_DATA) {
22486            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22487                    + Integer.toHexString(flags));
22488        }
22489
22490        final String volumeUuid = pkg.volumeUuid;
22491        final String packageName = pkg.packageName;
22492        final ApplicationInfo app = pkg.applicationInfo;
22493        final int appId = UserHandle.getAppId(app.uid);
22494
22495        Preconditions.checkNotNull(app.seInfo);
22496
22497        long ceDataInode = -1;
22498        try {
22499            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22500                    appId, app.seInfo, app.targetSdkVersion);
22501        } catch (InstallerException e) {
22502            if (app.isSystemApp()) {
22503                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22504                        + ", but trying to recover: " + e);
22505                destroyAppDataLeafLIF(pkg, userId, flags);
22506                try {
22507                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22508                            appId, app.seInfo, app.targetSdkVersion);
22509                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22510                } catch (InstallerException e2) {
22511                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22512                }
22513            } else {
22514                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22515            }
22516        }
22517
22518        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22519            // TODO: mark this structure as dirty so we persist it!
22520            synchronized (mPackages) {
22521                final PackageSetting ps = mSettings.mPackages.get(packageName);
22522                if (ps != null) {
22523                    ps.setCeDataInode(ceDataInode, userId);
22524                }
22525            }
22526        }
22527
22528        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22529    }
22530
22531    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22532        if (pkg == null) {
22533            Slog.wtf(TAG, "Package was null!", new Throwable());
22534            return;
22535        }
22536        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22537        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22538        for (int i = 0; i < childCount; i++) {
22539            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22540        }
22541    }
22542
22543    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22544        final String volumeUuid = pkg.volumeUuid;
22545        final String packageName = pkg.packageName;
22546        final ApplicationInfo app = pkg.applicationInfo;
22547
22548        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22549            // Create a native library symlink only if we have native libraries
22550            // and if the native libraries are 32 bit libraries. We do not provide
22551            // this symlink for 64 bit libraries.
22552            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22553                final String nativeLibPath = app.nativeLibraryDir;
22554                try {
22555                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22556                            nativeLibPath, userId);
22557                } catch (InstallerException e) {
22558                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22559                }
22560            }
22561        }
22562    }
22563
22564    /**
22565     * For system apps on non-FBE devices, this method migrates any existing
22566     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22567     * requested by the app.
22568     */
22569    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22570        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
22571                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22572            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22573                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22574            try {
22575                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22576                        storageTarget);
22577            } catch (InstallerException e) {
22578                logCriticalInfo(Log.WARN,
22579                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22580            }
22581            return true;
22582        } else {
22583            return false;
22584        }
22585    }
22586
22587    public PackageFreezer freezePackage(String packageName, String killReason) {
22588        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22589    }
22590
22591    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22592        return new PackageFreezer(packageName, userId, killReason);
22593    }
22594
22595    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22596            String killReason) {
22597        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22598    }
22599
22600    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22601            String killReason) {
22602        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22603            return new PackageFreezer();
22604        } else {
22605            return freezePackage(packageName, userId, killReason);
22606        }
22607    }
22608
22609    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22610            String killReason) {
22611        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22612    }
22613
22614    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22615            String killReason) {
22616        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22617            return new PackageFreezer();
22618        } else {
22619            return freezePackage(packageName, userId, killReason);
22620        }
22621    }
22622
22623    /**
22624     * Class that freezes and kills the given package upon creation, and
22625     * unfreezes it upon closing. This is typically used when doing surgery on
22626     * app code/data to prevent the app from running while you're working.
22627     */
22628    private class PackageFreezer implements AutoCloseable {
22629        private final String mPackageName;
22630        private final PackageFreezer[] mChildren;
22631
22632        private final boolean mWeFroze;
22633
22634        private final AtomicBoolean mClosed = new AtomicBoolean();
22635        private final CloseGuard mCloseGuard = CloseGuard.get();
22636
22637        /**
22638         * Create and return a stub freezer that doesn't actually do anything,
22639         * typically used when someone requested
22640         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22641         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22642         */
22643        public PackageFreezer() {
22644            mPackageName = null;
22645            mChildren = null;
22646            mWeFroze = false;
22647            mCloseGuard.open("close");
22648        }
22649
22650        public PackageFreezer(String packageName, int userId, String killReason) {
22651            synchronized (mPackages) {
22652                mPackageName = packageName;
22653                mWeFroze = mFrozenPackages.add(mPackageName);
22654
22655                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22656                if (ps != null) {
22657                    killApplication(ps.name, ps.appId, userId, killReason);
22658                }
22659
22660                final PackageParser.Package p = mPackages.get(packageName);
22661                if (p != null && p.childPackages != null) {
22662                    final int N = p.childPackages.size();
22663                    mChildren = new PackageFreezer[N];
22664                    for (int i = 0; i < N; i++) {
22665                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22666                                userId, killReason);
22667                    }
22668                } else {
22669                    mChildren = null;
22670                }
22671            }
22672            mCloseGuard.open("close");
22673        }
22674
22675        @Override
22676        protected void finalize() throws Throwable {
22677            try {
22678                if (mCloseGuard != null) {
22679                    mCloseGuard.warnIfOpen();
22680                }
22681
22682                close();
22683            } finally {
22684                super.finalize();
22685            }
22686        }
22687
22688        @Override
22689        public void close() {
22690            mCloseGuard.close();
22691            if (mClosed.compareAndSet(false, true)) {
22692                synchronized (mPackages) {
22693                    if (mWeFroze) {
22694                        mFrozenPackages.remove(mPackageName);
22695                    }
22696
22697                    if (mChildren != null) {
22698                        for (PackageFreezer freezer : mChildren) {
22699                            freezer.close();
22700                        }
22701                    }
22702                }
22703            }
22704        }
22705    }
22706
22707    /**
22708     * Verify that given package is currently frozen.
22709     */
22710    private void checkPackageFrozen(String packageName) {
22711        synchronized (mPackages) {
22712            if (!mFrozenPackages.contains(packageName)) {
22713                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22714            }
22715        }
22716    }
22717
22718    @Override
22719    public int movePackage(final String packageName, final String volumeUuid) {
22720        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22721
22722        final int callingUid = Binder.getCallingUid();
22723        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22724        final int moveId = mNextMoveId.getAndIncrement();
22725        mHandler.post(new Runnable() {
22726            @Override
22727            public void run() {
22728                try {
22729                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22730                } catch (PackageManagerException e) {
22731                    Slog.w(TAG, "Failed to move " + packageName, e);
22732                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22733                }
22734            }
22735        });
22736        return moveId;
22737    }
22738
22739    private void movePackageInternal(final String packageName, final String volumeUuid,
22740            final int moveId, final int callingUid, UserHandle user)
22741                    throws PackageManagerException {
22742        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22743        final PackageManager pm = mContext.getPackageManager();
22744
22745        final boolean currentAsec;
22746        final String currentVolumeUuid;
22747        final File codeFile;
22748        final String installerPackageName;
22749        final String packageAbiOverride;
22750        final int appId;
22751        final String seinfo;
22752        final String label;
22753        final int targetSdkVersion;
22754        final PackageFreezer freezer;
22755        final int[] installedUserIds;
22756
22757        // reader
22758        synchronized (mPackages) {
22759            final PackageParser.Package pkg = mPackages.get(packageName);
22760            final PackageSetting ps = mSettings.mPackages.get(packageName);
22761            if (pkg == null
22762                    || ps == null
22763                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22764                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22765            }
22766            if (pkg.applicationInfo.isSystemApp()) {
22767                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22768                        "Cannot move system application");
22769            }
22770
22771            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22772            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22773                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22774            if (isInternalStorage && !allow3rdPartyOnInternal) {
22775                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22776                        "3rd party apps are not allowed on internal storage");
22777            }
22778
22779            if (pkg.applicationInfo.isExternalAsec()) {
22780                currentAsec = true;
22781                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22782            } else if (pkg.applicationInfo.isForwardLocked()) {
22783                currentAsec = true;
22784                currentVolumeUuid = "forward_locked";
22785            } else {
22786                currentAsec = false;
22787                currentVolumeUuid = ps.volumeUuid;
22788
22789                final File probe = new File(pkg.codePath);
22790                final File probeOat = new File(probe, "oat");
22791                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22792                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22793                            "Move only supported for modern cluster style installs");
22794                }
22795            }
22796
22797            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22798                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22799                        "Package already moved to " + volumeUuid);
22800            }
22801            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22802                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22803                        "Device admin cannot be moved");
22804            }
22805
22806            if (mFrozenPackages.contains(packageName)) {
22807                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22808                        "Failed to move already frozen package");
22809            }
22810
22811            codeFile = new File(pkg.codePath);
22812            installerPackageName = ps.installerPackageName;
22813            packageAbiOverride = ps.cpuAbiOverrideString;
22814            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22815            seinfo = pkg.applicationInfo.seInfo;
22816            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22817            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22818            freezer = freezePackage(packageName, "movePackageInternal");
22819            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22820        }
22821
22822        final Bundle extras = new Bundle();
22823        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22824        extras.putString(Intent.EXTRA_TITLE, label);
22825        mMoveCallbacks.notifyCreated(moveId, extras);
22826
22827        int installFlags;
22828        final boolean moveCompleteApp;
22829        final File measurePath;
22830
22831        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22832            installFlags = INSTALL_INTERNAL;
22833            moveCompleteApp = !currentAsec;
22834            measurePath = Environment.getDataAppDirectory(volumeUuid);
22835        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22836            installFlags = INSTALL_EXTERNAL;
22837            moveCompleteApp = false;
22838            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22839        } else {
22840            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22841            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22842                    || !volume.isMountedWritable()) {
22843                freezer.close();
22844                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22845                        "Move location not mounted private volume");
22846            }
22847
22848            Preconditions.checkState(!currentAsec);
22849
22850            installFlags = INSTALL_INTERNAL;
22851            moveCompleteApp = true;
22852            measurePath = Environment.getDataAppDirectory(volumeUuid);
22853        }
22854
22855        // If we're moving app data around, we need all the users unlocked
22856        if (moveCompleteApp) {
22857            for (int userId : installedUserIds) {
22858                if (StorageManager.isFileEncryptedNativeOrEmulated()
22859                        && !StorageManager.isUserKeyUnlocked(userId)) {
22860                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22861                            "User " + userId + " must be unlocked");
22862                }
22863            }
22864        }
22865
22866        final PackageStats stats = new PackageStats(null, -1);
22867        synchronized (mInstaller) {
22868            for (int userId : installedUserIds) {
22869                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22870                    freezer.close();
22871                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22872                            "Failed to measure package size");
22873                }
22874            }
22875        }
22876
22877        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22878                + stats.dataSize);
22879
22880        final long startFreeBytes = measurePath.getUsableSpace();
22881        final long sizeBytes;
22882        if (moveCompleteApp) {
22883            sizeBytes = stats.codeSize + stats.dataSize;
22884        } else {
22885            sizeBytes = stats.codeSize;
22886        }
22887
22888        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22889            freezer.close();
22890            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22891                    "Not enough free space to move");
22892        }
22893
22894        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22895
22896        final CountDownLatch installedLatch = new CountDownLatch(1);
22897        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22898            @Override
22899            public void onUserActionRequired(Intent intent) throws RemoteException {
22900                throw new IllegalStateException();
22901            }
22902
22903            @Override
22904            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22905                    Bundle extras) throws RemoteException {
22906                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22907                        + PackageManager.installStatusToString(returnCode, msg));
22908
22909                installedLatch.countDown();
22910                freezer.close();
22911
22912                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22913                switch (status) {
22914                    case PackageInstaller.STATUS_SUCCESS:
22915                        mMoveCallbacks.notifyStatusChanged(moveId,
22916                                PackageManager.MOVE_SUCCEEDED);
22917                        break;
22918                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22919                        mMoveCallbacks.notifyStatusChanged(moveId,
22920                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22921                        break;
22922                    default:
22923                        mMoveCallbacks.notifyStatusChanged(moveId,
22924                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22925                        break;
22926                }
22927            }
22928        };
22929
22930        final MoveInfo move;
22931        if (moveCompleteApp) {
22932            // Kick off a thread to report progress estimates
22933            new Thread() {
22934                @Override
22935                public void run() {
22936                    while (true) {
22937                        try {
22938                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22939                                break;
22940                            }
22941                        } catch (InterruptedException ignored) {
22942                        }
22943
22944                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22945                        final int progress = 10 + (int) MathUtils.constrain(
22946                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22947                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22948                    }
22949                }
22950            }.start();
22951
22952            final String dataAppName = codeFile.getName();
22953            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22954                    dataAppName, appId, seinfo, targetSdkVersion);
22955        } else {
22956            move = null;
22957        }
22958
22959        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22960
22961        final Message msg = mHandler.obtainMessage(INIT_COPY);
22962        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22963        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22964                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22965                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22966                PackageManager.INSTALL_REASON_UNKNOWN);
22967        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22968        msg.obj = params;
22969
22970        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22971                System.identityHashCode(msg.obj));
22972        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22973                System.identityHashCode(msg.obj));
22974
22975        mHandler.sendMessage(msg);
22976    }
22977
22978    @Override
22979    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22980        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22981
22982        final int realMoveId = mNextMoveId.getAndIncrement();
22983        final Bundle extras = new Bundle();
22984        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22985        mMoveCallbacks.notifyCreated(realMoveId, extras);
22986
22987        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22988            @Override
22989            public void onCreated(int moveId, Bundle extras) {
22990                // Ignored
22991            }
22992
22993            @Override
22994            public void onStatusChanged(int moveId, int status, long estMillis) {
22995                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22996            }
22997        };
22998
22999        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23000        storage.setPrimaryStorageUuid(volumeUuid, callback);
23001        return realMoveId;
23002    }
23003
23004    @Override
23005    public int getMoveStatus(int moveId) {
23006        mContext.enforceCallingOrSelfPermission(
23007                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23008        return mMoveCallbacks.mLastStatus.get(moveId);
23009    }
23010
23011    @Override
23012    public void registerMoveCallback(IPackageMoveObserver callback) {
23013        mContext.enforceCallingOrSelfPermission(
23014                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23015        mMoveCallbacks.register(callback);
23016    }
23017
23018    @Override
23019    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23020        mContext.enforceCallingOrSelfPermission(
23021                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23022        mMoveCallbacks.unregister(callback);
23023    }
23024
23025    @Override
23026    public boolean setInstallLocation(int loc) {
23027        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23028                null);
23029        if (getInstallLocation() == loc) {
23030            return true;
23031        }
23032        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23033                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23034            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23035                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23036            return true;
23037        }
23038        return false;
23039   }
23040
23041    @Override
23042    public int getInstallLocation() {
23043        // allow instant app access
23044        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23045                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23046                PackageHelper.APP_INSTALL_AUTO);
23047    }
23048
23049    /** Called by UserManagerService */
23050    void cleanUpUser(UserManagerService userManager, int userHandle) {
23051        synchronized (mPackages) {
23052            mDirtyUsers.remove(userHandle);
23053            mUserNeedsBadging.delete(userHandle);
23054            mSettings.removeUserLPw(userHandle);
23055            mPendingBroadcasts.remove(userHandle);
23056            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23057            removeUnusedPackagesLPw(userManager, userHandle);
23058        }
23059    }
23060
23061    /**
23062     * We're removing userHandle and would like to remove any downloaded packages
23063     * that are no longer in use by any other user.
23064     * @param userHandle the user being removed
23065     */
23066    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23067        final boolean DEBUG_CLEAN_APKS = false;
23068        int [] users = userManager.getUserIds();
23069        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23070        while (psit.hasNext()) {
23071            PackageSetting ps = psit.next();
23072            if (ps.pkg == null) {
23073                continue;
23074            }
23075            final String packageName = ps.pkg.packageName;
23076            // Skip over if system app
23077            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23078                continue;
23079            }
23080            if (DEBUG_CLEAN_APKS) {
23081                Slog.i(TAG, "Checking package " + packageName);
23082            }
23083            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23084            if (keep) {
23085                if (DEBUG_CLEAN_APKS) {
23086                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23087                }
23088            } else {
23089                for (int i = 0; i < users.length; i++) {
23090                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23091                        keep = true;
23092                        if (DEBUG_CLEAN_APKS) {
23093                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23094                                    + users[i]);
23095                        }
23096                        break;
23097                    }
23098                }
23099            }
23100            if (!keep) {
23101                if (DEBUG_CLEAN_APKS) {
23102                    Slog.i(TAG, "  Removing package " + packageName);
23103                }
23104                mHandler.post(new Runnable() {
23105                    public void run() {
23106                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23107                                userHandle, 0);
23108                    } //end run
23109                });
23110            }
23111        }
23112    }
23113
23114    /** Called by UserManagerService */
23115    void createNewUser(int userId, String[] disallowedPackages) {
23116        synchronized (mInstallLock) {
23117            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23118        }
23119        synchronized (mPackages) {
23120            scheduleWritePackageRestrictionsLocked(userId);
23121            scheduleWritePackageListLocked(userId);
23122            applyFactoryDefaultBrowserLPw(userId);
23123            primeDomainVerificationsLPw(userId);
23124        }
23125    }
23126
23127    void onNewUserCreated(final int userId) {
23128        synchronized(mPackages) {
23129            mDefaultPermissionPolicy.grantDefaultPermissions(mPackages.values(), userId);
23130            // If permission review for legacy apps is required, we represent
23131            // dagerous permissions for such apps as always granted runtime
23132            // permissions to keep per user flag state whether review is needed.
23133            // Hence, if a new user is added we have to propagate dangerous
23134            // permission grants for these legacy apps.
23135            if (mPermissionReviewRequired) {
23136                updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
23137                        | UPDATE_PERMISSIONS_REPLACE_ALL);
23138            }
23139        }
23140    }
23141
23142    @Override
23143    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23144        mContext.enforceCallingOrSelfPermission(
23145                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23146                "Only package verification agents can read the verifier device identity");
23147
23148        synchronized (mPackages) {
23149            return mSettings.getVerifierDeviceIdentityLPw();
23150        }
23151    }
23152
23153    @Override
23154    public void setPermissionEnforced(String permission, boolean enforced) {
23155        // TODO: Now that we no longer change GID for storage, this should to away.
23156        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23157                "setPermissionEnforced");
23158        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23159            synchronized (mPackages) {
23160                if (mSettings.mReadExternalStorageEnforced == null
23161                        || mSettings.mReadExternalStorageEnforced != enforced) {
23162                    mSettings.mReadExternalStorageEnforced =
23163                            enforced ? Boolean.TRUE : Boolean.FALSE;
23164                    mSettings.writeLPr();
23165                }
23166            }
23167            // kill any non-foreground processes so we restart them and
23168            // grant/revoke the GID.
23169            final IActivityManager am = ActivityManager.getService();
23170            if (am != null) {
23171                final long token = Binder.clearCallingIdentity();
23172                try {
23173                    am.killProcessesBelowForeground("setPermissionEnforcement");
23174                } catch (RemoteException e) {
23175                } finally {
23176                    Binder.restoreCallingIdentity(token);
23177                }
23178            }
23179        } else {
23180            throw new IllegalArgumentException("No selective enforcement for " + permission);
23181        }
23182    }
23183
23184    @Override
23185    @Deprecated
23186    public boolean isPermissionEnforced(String permission) {
23187        // allow instant applications
23188        return true;
23189    }
23190
23191    @Override
23192    public boolean isStorageLow() {
23193        // allow instant applications
23194        final long token = Binder.clearCallingIdentity();
23195        try {
23196            final DeviceStorageMonitorInternal
23197                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23198            if (dsm != null) {
23199                return dsm.isMemoryLow();
23200            } else {
23201                return false;
23202            }
23203        } finally {
23204            Binder.restoreCallingIdentity(token);
23205        }
23206    }
23207
23208    @Override
23209    public IPackageInstaller getPackageInstaller() {
23210        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23211            return null;
23212        }
23213        return mInstallerService;
23214    }
23215
23216    private boolean userNeedsBadging(int userId) {
23217        int index = mUserNeedsBadging.indexOfKey(userId);
23218        if (index < 0) {
23219            final UserInfo userInfo;
23220            final long token = Binder.clearCallingIdentity();
23221            try {
23222                userInfo = sUserManager.getUserInfo(userId);
23223            } finally {
23224                Binder.restoreCallingIdentity(token);
23225            }
23226            final boolean b;
23227            if (userInfo != null && userInfo.isManagedProfile()) {
23228                b = true;
23229            } else {
23230                b = false;
23231            }
23232            mUserNeedsBadging.put(userId, b);
23233            return b;
23234        }
23235        return mUserNeedsBadging.valueAt(index);
23236    }
23237
23238    @Override
23239    public KeySet getKeySetByAlias(String packageName, String alias) {
23240        if (packageName == null || alias == null) {
23241            return null;
23242        }
23243        synchronized(mPackages) {
23244            final PackageParser.Package pkg = mPackages.get(packageName);
23245            if (pkg == null) {
23246                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23247                throw new IllegalArgumentException("Unknown package: " + packageName);
23248            }
23249            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23250            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
23251                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
23252                throw new IllegalArgumentException("Unknown package: " + packageName);
23253            }
23254            KeySetManagerService ksms = mSettings.mKeySetManagerService;
23255            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23256        }
23257    }
23258
23259    @Override
23260    public KeySet getSigningKeySet(String packageName) {
23261        if (packageName == null) {
23262            return null;
23263        }
23264        synchronized(mPackages) {
23265            final int callingUid = Binder.getCallingUid();
23266            final int callingUserId = UserHandle.getUserId(callingUid);
23267            final PackageParser.Package pkg = mPackages.get(packageName);
23268            if (pkg == null) {
23269                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23270                throw new IllegalArgumentException("Unknown package: " + packageName);
23271            }
23272            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23273            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23274                // filter and pretend the package doesn't exist
23275                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23276                        + ", uid:" + callingUid);
23277                throw new IllegalArgumentException("Unknown package: " + packageName);
23278            }
23279            if (pkg.applicationInfo.uid != callingUid
23280                    && Process.SYSTEM_UID != callingUid) {
23281                throw new SecurityException("May not access signing KeySet of other apps.");
23282            }
23283            KeySetManagerService ksms = mSettings.mKeySetManagerService;
23284            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23285        }
23286    }
23287
23288    @Override
23289    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23290        final int callingUid = Binder.getCallingUid();
23291        if (getInstantAppPackageName(callingUid) != null) {
23292            return false;
23293        }
23294        if (packageName == null || ks == null) {
23295            return false;
23296        }
23297        synchronized(mPackages) {
23298            final PackageParser.Package pkg = mPackages.get(packageName);
23299            if (pkg == null
23300                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23301                            UserHandle.getUserId(callingUid))) {
23302                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23303                throw new IllegalArgumentException("Unknown package: " + packageName);
23304            }
23305            IBinder ksh = ks.getToken();
23306            if (ksh instanceof KeySetHandle) {
23307                KeySetManagerService ksms = mSettings.mKeySetManagerService;
23308                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23309            }
23310            return false;
23311        }
23312    }
23313
23314    @Override
23315    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23316        final int callingUid = Binder.getCallingUid();
23317        if (getInstantAppPackageName(callingUid) != null) {
23318            return false;
23319        }
23320        if (packageName == null || ks == null) {
23321            return false;
23322        }
23323        synchronized(mPackages) {
23324            final PackageParser.Package pkg = mPackages.get(packageName);
23325            if (pkg == null
23326                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23327                            UserHandle.getUserId(callingUid))) {
23328                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23329                throw new IllegalArgumentException("Unknown package: " + packageName);
23330            }
23331            IBinder ksh = ks.getToken();
23332            if (ksh instanceof KeySetHandle) {
23333                KeySetManagerService ksms = mSettings.mKeySetManagerService;
23334                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23335            }
23336            return false;
23337        }
23338    }
23339
23340    private void deletePackageIfUnusedLPr(final String packageName) {
23341        PackageSetting ps = mSettings.mPackages.get(packageName);
23342        if (ps == null) {
23343            return;
23344        }
23345        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23346            // TODO Implement atomic delete if package is unused
23347            // It is currently possible that the package will be deleted even if it is installed
23348            // after this method returns.
23349            mHandler.post(new Runnable() {
23350                public void run() {
23351                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23352                            0, PackageManager.DELETE_ALL_USERS);
23353                }
23354            });
23355        }
23356    }
23357
23358    /**
23359     * Check and throw if the given before/after packages would be considered a
23360     * downgrade.
23361     */
23362    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23363            throws PackageManagerException {
23364        if (after.versionCode < before.mVersionCode) {
23365            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23366                    "Update version code " + after.versionCode + " is older than current "
23367                    + before.mVersionCode);
23368        } else if (after.versionCode == before.mVersionCode) {
23369            if (after.baseRevisionCode < before.baseRevisionCode) {
23370                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23371                        "Update base revision code " + after.baseRevisionCode
23372                        + " is older than current " + before.baseRevisionCode);
23373            }
23374
23375            if (!ArrayUtils.isEmpty(after.splitNames)) {
23376                for (int i = 0; i < after.splitNames.length; i++) {
23377                    final String splitName = after.splitNames[i];
23378                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23379                    if (j != -1) {
23380                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23381                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23382                                    "Update split " + splitName + " revision code "
23383                                    + after.splitRevisionCodes[i] + " is older than current "
23384                                    + before.splitRevisionCodes[j]);
23385                        }
23386                    }
23387                }
23388            }
23389        }
23390    }
23391
23392    private static class MoveCallbacks extends Handler {
23393        private static final int MSG_CREATED = 1;
23394        private static final int MSG_STATUS_CHANGED = 2;
23395
23396        private final RemoteCallbackList<IPackageMoveObserver>
23397                mCallbacks = new RemoteCallbackList<>();
23398
23399        private final SparseIntArray mLastStatus = new SparseIntArray();
23400
23401        public MoveCallbacks(Looper looper) {
23402            super(looper);
23403        }
23404
23405        public void register(IPackageMoveObserver callback) {
23406            mCallbacks.register(callback);
23407        }
23408
23409        public void unregister(IPackageMoveObserver callback) {
23410            mCallbacks.unregister(callback);
23411        }
23412
23413        @Override
23414        public void handleMessage(Message msg) {
23415            final SomeArgs args = (SomeArgs) msg.obj;
23416            final int n = mCallbacks.beginBroadcast();
23417            for (int i = 0; i < n; i++) {
23418                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23419                try {
23420                    invokeCallback(callback, msg.what, args);
23421                } catch (RemoteException ignored) {
23422                }
23423            }
23424            mCallbacks.finishBroadcast();
23425            args.recycle();
23426        }
23427
23428        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23429                throws RemoteException {
23430            switch (what) {
23431                case MSG_CREATED: {
23432                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23433                    break;
23434                }
23435                case MSG_STATUS_CHANGED: {
23436                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23437                    break;
23438                }
23439            }
23440        }
23441
23442        private void notifyCreated(int moveId, Bundle extras) {
23443            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23444
23445            final SomeArgs args = SomeArgs.obtain();
23446            args.argi1 = moveId;
23447            args.arg2 = extras;
23448            obtainMessage(MSG_CREATED, args).sendToTarget();
23449        }
23450
23451        private void notifyStatusChanged(int moveId, int status) {
23452            notifyStatusChanged(moveId, status, -1);
23453        }
23454
23455        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23456            Slog.v(TAG, "Move " + moveId + " status " + status);
23457
23458            final SomeArgs args = SomeArgs.obtain();
23459            args.argi1 = moveId;
23460            args.argi2 = status;
23461            args.arg3 = estMillis;
23462            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23463
23464            synchronized (mLastStatus) {
23465                mLastStatus.put(moveId, status);
23466            }
23467        }
23468    }
23469
23470    private final static class OnPermissionChangeListeners extends Handler {
23471        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23472
23473        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23474                new RemoteCallbackList<>();
23475
23476        public OnPermissionChangeListeners(Looper looper) {
23477            super(looper);
23478        }
23479
23480        @Override
23481        public void handleMessage(Message msg) {
23482            switch (msg.what) {
23483                case MSG_ON_PERMISSIONS_CHANGED: {
23484                    final int uid = msg.arg1;
23485                    handleOnPermissionsChanged(uid);
23486                } break;
23487            }
23488        }
23489
23490        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23491            mPermissionListeners.register(listener);
23492
23493        }
23494
23495        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23496            mPermissionListeners.unregister(listener);
23497        }
23498
23499        public void onPermissionsChanged(int uid) {
23500            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23501                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23502            }
23503        }
23504
23505        private void handleOnPermissionsChanged(int uid) {
23506            final int count = mPermissionListeners.beginBroadcast();
23507            try {
23508                for (int i = 0; i < count; i++) {
23509                    IOnPermissionsChangeListener callback = mPermissionListeners
23510                            .getBroadcastItem(i);
23511                    try {
23512                        callback.onPermissionsChanged(uid);
23513                    } catch (RemoteException e) {
23514                        Log.e(TAG, "Permission listener is dead", e);
23515                    }
23516                }
23517            } finally {
23518                mPermissionListeners.finishBroadcast();
23519            }
23520        }
23521    }
23522
23523    private class PackageManagerNative extends IPackageManagerNative.Stub {
23524        @Override
23525        public String[] getNamesForUids(int[] uids) throws RemoteException {
23526            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23527            // massage results so they can be parsed by the native binder
23528            for (int i = results.length - 1; i >= 0; --i) {
23529                if (results[i] == null) {
23530                    results[i] = "";
23531                }
23532            }
23533            return results;
23534        }
23535
23536        // NB: this differentiates between preloads and sideloads
23537        @Override
23538        public String getInstallerForPackage(String packageName) throws RemoteException {
23539            final String installerName = getInstallerPackageName(packageName);
23540            if (!TextUtils.isEmpty(installerName)) {
23541                return installerName;
23542            }
23543            // differentiate between preload and sideload
23544            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23545            ApplicationInfo appInfo = getApplicationInfo(packageName,
23546                                    /*flags*/ 0,
23547                                    /*userId*/ callingUser);
23548            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23549                return "preload";
23550            }
23551            return "";
23552        }
23553
23554        @Override
23555        public int getVersionCodeForPackage(String packageName) throws RemoteException {
23556            try {
23557                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23558                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23559                if (pInfo != null) {
23560                    return pInfo.versionCode;
23561                }
23562            } catch (Exception e) {
23563            }
23564            return 0;
23565        }
23566    }
23567
23568    private class PackageManagerInternalImpl extends PackageManagerInternal {
23569        @Override
23570        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23571                int flagValues, int userId) {
23572            PackageManagerService.this.updatePermissionFlags(
23573                    permName, packageName, flagMask, flagValues, userId);
23574        }
23575
23576        @Override
23577        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23578            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23579        }
23580
23581        @Override
23582        public PackageParser.PermissionGroup getPermissionGroupTEMP(String groupName) {
23583            synchronized (mPackages) {
23584                return mPermissionGroups.get(groupName);
23585            }
23586        }
23587
23588        @Override
23589        public boolean isInstantApp(String packageName, int userId) {
23590            return PackageManagerService.this.isInstantApp(packageName, userId);
23591        }
23592
23593        @Override
23594        public String getInstantAppPackageName(int uid) {
23595            return PackageManagerService.this.getInstantAppPackageName(uid);
23596        }
23597
23598        @Override
23599        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23600            synchronized (mPackages) {
23601                return PackageManagerService.this.filterAppAccessLPr(
23602                        (PackageSetting) pkg.mExtras, callingUid, userId);
23603            }
23604        }
23605
23606        @Override
23607        public PackageParser.Package getPackage(String packageName) {
23608            synchronized (mPackages) {
23609                packageName = resolveInternalPackageNameLPr(
23610                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23611                return mPackages.get(packageName);
23612            }
23613        }
23614
23615        @Override
23616        public PackageParser.Package getDisabledPackage(String packageName) {
23617            synchronized (mPackages) {
23618                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23619                return (ps != null) ? ps.pkg : null;
23620            }
23621        }
23622
23623        @Override
23624        public String getKnownPackageName(int knownPackage, int userId) {
23625            switch(knownPackage) {
23626                case PackageManagerInternal.PACKAGE_BROWSER:
23627                    return getDefaultBrowserPackageName(userId);
23628                case PackageManagerInternal.PACKAGE_INSTALLER:
23629                    return mRequiredInstallerPackage;
23630                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23631                    return mSetupWizardPackage;
23632                case PackageManagerInternal.PACKAGE_SYSTEM:
23633                    return "android";
23634                case PackageManagerInternal.PACKAGE_VERIFIER:
23635                    return mRequiredVerifierPackage;
23636            }
23637            return null;
23638        }
23639
23640        @Override
23641        public boolean isResolveActivityComponent(ComponentInfo component) {
23642            return mResolveActivity.packageName.equals(component.packageName)
23643                    && mResolveActivity.name.equals(component.name);
23644        }
23645
23646        @Override
23647        public void setLocationPackagesProvider(PackagesProvider provider) {
23648            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23649        }
23650
23651        @Override
23652        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23653            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23654        }
23655
23656        @Override
23657        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23658            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23659        }
23660
23661        @Override
23662        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23663            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23664        }
23665
23666        @Override
23667        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23668            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23669        }
23670
23671        @Override
23672        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23673            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23674        }
23675
23676        @Override
23677        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23678            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23679        }
23680
23681        @Override
23682        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23683            synchronized (mPackages) {
23684                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23685            }
23686            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23687        }
23688
23689        @Override
23690        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23691            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23692                    packageName, userId);
23693        }
23694
23695        @Override
23696        public void setKeepUninstalledPackages(final List<String> packageList) {
23697            Preconditions.checkNotNull(packageList);
23698            List<String> removedFromList = null;
23699            synchronized (mPackages) {
23700                if (mKeepUninstalledPackages != null) {
23701                    final int packagesCount = mKeepUninstalledPackages.size();
23702                    for (int i = 0; i < packagesCount; i++) {
23703                        String oldPackage = mKeepUninstalledPackages.get(i);
23704                        if (packageList != null && packageList.contains(oldPackage)) {
23705                            continue;
23706                        }
23707                        if (removedFromList == null) {
23708                            removedFromList = new ArrayList<>();
23709                        }
23710                        removedFromList.add(oldPackage);
23711                    }
23712                }
23713                mKeepUninstalledPackages = new ArrayList<>(packageList);
23714                if (removedFromList != null) {
23715                    final int removedCount = removedFromList.size();
23716                    for (int i = 0; i < removedCount; i++) {
23717                        deletePackageIfUnusedLPr(removedFromList.get(i));
23718                    }
23719                }
23720            }
23721        }
23722
23723        @Override
23724        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23725            synchronized (mPackages) {
23726                // If we do not support permission review, done.
23727                if (!mPermissionReviewRequired) {
23728                    return false;
23729                }
23730
23731                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
23732                if (packageSetting == null) {
23733                    return false;
23734                }
23735
23736                // Permission review applies only to apps not supporting the new permission model.
23737                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
23738                    return false;
23739                }
23740
23741                // Legacy apps have the permission and get user consent on launch.
23742                PermissionsState permissionsState = packageSetting.getPermissionsState();
23743                return permissionsState.isPermissionReviewRequired(userId);
23744            }
23745        }
23746
23747        @Override
23748        public PackageInfo getPackageInfo(
23749                String packageName, int flags, int filterCallingUid, int userId) {
23750            return PackageManagerService.this
23751                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23752                            flags, filterCallingUid, userId);
23753        }
23754
23755        @Override
23756        public ApplicationInfo getApplicationInfo(
23757                String packageName, int flags, int filterCallingUid, int userId) {
23758            return PackageManagerService.this
23759                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23760        }
23761
23762        @Override
23763        public ActivityInfo getActivityInfo(
23764                ComponentName component, int flags, int filterCallingUid, int userId) {
23765            return PackageManagerService.this
23766                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23767        }
23768
23769        @Override
23770        public List<ResolveInfo> queryIntentActivities(
23771                Intent intent, int flags, int filterCallingUid, int userId) {
23772            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23773            return PackageManagerService.this
23774                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23775                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23776        }
23777
23778        @Override
23779        public List<ResolveInfo> queryIntentServices(
23780                Intent intent, int flags, int callingUid, int userId) {
23781            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23782            return PackageManagerService.this
23783                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23784                            false);
23785        }
23786
23787        @Override
23788        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23789                int userId) {
23790            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23791        }
23792
23793        @Override
23794        public void setDeviceAndProfileOwnerPackages(
23795                int deviceOwnerUserId, String deviceOwnerPackage,
23796                SparseArray<String> profileOwnerPackages) {
23797            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23798                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23799        }
23800
23801        @Override
23802        public boolean isPackageDataProtected(int userId, String packageName) {
23803            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23804        }
23805
23806        @Override
23807        public boolean isPackageEphemeral(int userId, String packageName) {
23808            synchronized (mPackages) {
23809                final PackageSetting ps = mSettings.mPackages.get(packageName);
23810                return ps != null ? ps.getInstantApp(userId) : false;
23811            }
23812        }
23813
23814        @Override
23815        public boolean wasPackageEverLaunched(String packageName, int userId) {
23816            synchronized (mPackages) {
23817                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23818            }
23819        }
23820
23821        @Override
23822        public void grantRuntimePermission(String packageName, String permName, int userId,
23823                boolean overridePolicy) {
23824            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23825                    permName, packageName, overridePolicy, getCallingUid(), userId,
23826                    mPermissionCallback);
23827        }
23828
23829        @Override
23830        public void revokeRuntimePermission(String packageName, String permName, int userId,
23831                boolean overridePolicy) {
23832            mPermissionManager.revokeRuntimePermission(
23833                    permName, packageName, overridePolicy, getCallingUid(), userId,
23834                    mPermissionCallback);
23835        }
23836
23837        @Override
23838        public String getNameForUid(int uid) {
23839            return PackageManagerService.this.getNameForUid(uid);
23840        }
23841
23842        @Override
23843        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23844                Intent origIntent, String resolvedType, String callingPackage,
23845                Bundle verificationBundle, int userId) {
23846            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23847                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23848                    userId);
23849        }
23850
23851        @Override
23852        public void grantEphemeralAccess(int userId, Intent intent,
23853                int targetAppId, int ephemeralAppId) {
23854            synchronized (mPackages) {
23855                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23856                        targetAppId, ephemeralAppId);
23857            }
23858        }
23859
23860        @Override
23861        public boolean isInstantAppInstallerComponent(ComponentName component) {
23862            synchronized (mPackages) {
23863                return mInstantAppInstallerActivity != null
23864                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23865            }
23866        }
23867
23868        @Override
23869        public void pruneInstantApps() {
23870            mInstantAppRegistry.pruneInstantApps();
23871        }
23872
23873        @Override
23874        public String getSetupWizardPackageName() {
23875            return mSetupWizardPackage;
23876        }
23877
23878        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23879            if (policy != null) {
23880                mExternalSourcesPolicy = policy;
23881            }
23882        }
23883
23884        @Override
23885        public boolean isPackagePersistent(String packageName) {
23886            synchronized (mPackages) {
23887                PackageParser.Package pkg = mPackages.get(packageName);
23888                return pkg != null
23889                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23890                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23891                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23892                        : false;
23893            }
23894        }
23895
23896        @Override
23897        public List<PackageInfo> getOverlayPackages(int userId) {
23898            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23899            synchronized (mPackages) {
23900                for (PackageParser.Package p : mPackages.values()) {
23901                    if (p.mOverlayTarget != null) {
23902                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23903                        if (pkg != null) {
23904                            overlayPackages.add(pkg);
23905                        }
23906                    }
23907                }
23908            }
23909            return overlayPackages;
23910        }
23911
23912        @Override
23913        public List<String> getTargetPackageNames(int userId) {
23914            List<String> targetPackages = new ArrayList<>();
23915            synchronized (mPackages) {
23916                for (PackageParser.Package p : mPackages.values()) {
23917                    if (p.mOverlayTarget == null) {
23918                        targetPackages.add(p.packageName);
23919                    }
23920                }
23921            }
23922            return targetPackages;
23923        }
23924
23925        @Override
23926        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23927                @Nullable List<String> overlayPackageNames) {
23928            synchronized (mPackages) {
23929                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23930                    Slog.e(TAG, "failed to find package " + targetPackageName);
23931                    return false;
23932                }
23933                ArrayList<String> overlayPaths = null;
23934                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
23935                    final int N = overlayPackageNames.size();
23936                    overlayPaths = new ArrayList<>(N);
23937                    for (int i = 0; i < N; i++) {
23938                        final String packageName = overlayPackageNames.get(i);
23939                        final PackageParser.Package pkg = mPackages.get(packageName);
23940                        if (pkg == null) {
23941                            Slog.e(TAG, "failed to find package " + packageName);
23942                            return false;
23943                        }
23944                        overlayPaths.add(pkg.baseCodePath);
23945                    }
23946                }
23947
23948                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
23949                ps.setOverlayPaths(overlayPaths, userId);
23950                return true;
23951            }
23952        }
23953
23954        @Override
23955        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23956                int flags, int userId, boolean resolveForStart) {
23957            return resolveIntentInternal(
23958                    intent, resolvedType, flags, userId, resolveForStart);
23959        }
23960
23961        @Override
23962        public ResolveInfo resolveService(Intent intent, String resolvedType,
23963                int flags, int userId, int callingUid) {
23964            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
23965        }
23966
23967        @Override
23968        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
23969            return PackageManagerService.this.resolveContentProviderInternal(
23970                    name, flags, userId);
23971        }
23972
23973        @Override
23974        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23975            synchronized (mPackages) {
23976                mIsolatedOwners.put(isolatedUid, ownerUid);
23977            }
23978        }
23979
23980        @Override
23981        public void removeIsolatedUid(int isolatedUid) {
23982            synchronized (mPackages) {
23983                mIsolatedOwners.delete(isolatedUid);
23984            }
23985        }
23986
23987        @Override
23988        public int getUidTargetSdkVersion(int uid) {
23989            synchronized (mPackages) {
23990                return getUidTargetSdkVersionLockedLPr(uid);
23991            }
23992        }
23993
23994        @Override
23995        public boolean canAccessInstantApps(int callingUid, int userId) {
23996            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
23997        }
23998
23999        @Override
24000        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
24001            synchronized (mPackages) {
24002                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
24003            }
24004        }
24005
24006        @Override
24007        public void notifyPackageUse(String packageName, int reason) {
24008            synchronized (mPackages) {
24009                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
24010            }
24011        }
24012    }
24013
24014    @Override
24015    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24016        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24017        synchronized (mPackages) {
24018            final long identity = Binder.clearCallingIdentity();
24019            try {
24020                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
24021                        packageNames, userId);
24022            } finally {
24023                Binder.restoreCallingIdentity(identity);
24024            }
24025        }
24026    }
24027
24028    @Override
24029    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24030        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24031        synchronized (mPackages) {
24032            final long identity = Binder.clearCallingIdentity();
24033            try {
24034                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
24035                        packageNames, userId);
24036            } finally {
24037                Binder.restoreCallingIdentity(identity);
24038            }
24039        }
24040    }
24041
24042    private static void enforceSystemOrPhoneCaller(String tag) {
24043        int callingUid = Binder.getCallingUid();
24044        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24045            throw new SecurityException(
24046                    "Cannot call " + tag + " from UID " + callingUid);
24047        }
24048    }
24049
24050    boolean isHistoricalPackageUsageAvailable() {
24051        return mPackageUsage.isHistoricalPackageUsageAvailable();
24052    }
24053
24054    /**
24055     * Return a <b>copy</b> of the collection of packages known to the package manager.
24056     * @return A copy of the values of mPackages.
24057     */
24058    Collection<PackageParser.Package> getPackages() {
24059        synchronized (mPackages) {
24060            return new ArrayList<>(mPackages.values());
24061        }
24062    }
24063
24064    /**
24065     * Logs process start information (including base APK hash) to the security log.
24066     * @hide
24067     */
24068    @Override
24069    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24070            String apkFile, int pid) {
24071        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24072            return;
24073        }
24074        if (!SecurityLog.isLoggingEnabled()) {
24075            return;
24076        }
24077        Bundle data = new Bundle();
24078        data.putLong("startTimestamp", System.currentTimeMillis());
24079        data.putString("processName", processName);
24080        data.putInt("uid", uid);
24081        data.putString("seinfo", seinfo);
24082        data.putString("apkFile", apkFile);
24083        data.putInt("pid", pid);
24084        Message msg = mProcessLoggingHandler.obtainMessage(
24085                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24086        msg.setData(data);
24087        mProcessLoggingHandler.sendMessage(msg);
24088    }
24089
24090    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24091        return mCompilerStats.getPackageStats(pkgName);
24092    }
24093
24094    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24095        return getOrCreateCompilerPackageStats(pkg.packageName);
24096    }
24097
24098    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24099        return mCompilerStats.getOrCreatePackageStats(pkgName);
24100    }
24101
24102    public void deleteCompilerPackageStats(String pkgName) {
24103        mCompilerStats.deletePackageStats(pkgName);
24104    }
24105
24106    @Override
24107    public int getInstallReason(String packageName, int userId) {
24108        final int callingUid = Binder.getCallingUid();
24109        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24110                true /* requireFullPermission */, false /* checkShell */,
24111                "get install reason");
24112        synchronized (mPackages) {
24113            final PackageSetting ps = mSettings.mPackages.get(packageName);
24114            if (filterAppAccessLPr(ps, callingUid, userId)) {
24115                return PackageManager.INSTALL_REASON_UNKNOWN;
24116            }
24117            if (ps != null) {
24118                return ps.getInstallReason(userId);
24119            }
24120        }
24121        return PackageManager.INSTALL_REASON_UNKNOWN;
24122    }
24123
24124    @Override
24125    public boolean canRequestPackageInstalls(String packageName, int userId) {
24126        return canRequestPackageInstallsInternal(packageName, 0, userId,
24127                true /* throwIfPermNotDeclared*/);
24128    }
24129
24130    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24131            boolean throwIfPermNotDeclared) {
24132        int callingUid = Binder.getCallingUid();
24133        int uid = getPackageUid(packageName, 0, userId);
24134        if (callingUid != uid && callingUid != Process.ROOT_UID
24135                && callingUid != Process.SYSTEM_UID) {
24136            throw new SecurityException(
24137                    "Caller uid " + callingUid + " does not own package " + packageName);
24138        }
24139        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24140        if (info == null) {
24141            return false;
24142        }
24143        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24144            return false;
24145        }
24146        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24147        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24148        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24149            if (throwIfPermNotDeclared) {
24150                throw new SecurityException("Need to declare " + appOpPermission
24151                        + " to call this api");
24152            } else {
24153                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24154                return false;
24155            }
24156        }
24157        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24158            return false;
24159        }
24160        if (mExternalSourcesPolicy != null) {
24161            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24162            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24163                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24164            }
24165        }
24166        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24167    }
24168
24169    @Override
24170    public ComponentName getInstantAppResolverSettingsComponent() {
24171        return mInstantAppResolverSettingsComponent;
24172    }
24173
24174    @Override
24175    public ComponentName getInstantAppInstallerComponent() {
24176        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24177            return null;
24178        }
24179        return mInstantAppInstallerActivity == null
24180                ? null : mInstantAppInstallerActivity.getComponentName();
24181    }
24182
24183    @Override
24184    public String getInstantAppAndroidId(String packageName, int userId) {
24185        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24186                "getInstantAppAndroidId");
24187        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
24188                true /* requireFullPermission */, false /* checkShell */,
24189                "getInstantAppAndroidId");
24190        // Make sure the target is an Instant App.
24191        if (!isInstantApp(packageName, userId)) {
24192            return null;
24193        }
24194        synchronized (mPackages) {
24195            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24196        }
24197    }
24198
24199    boolean canHaveOatDir(String packageName) {
24200        synchronized (mPackages) {
24201            PackageParser.Package p = mPackages.get(packageName);
24202            if (p == null) {
24203                return false;
24204            }
24205            return p.canHaveOatDir();
24206        }
24207    }
24208
24209    private String getOatDir(PackageParser.Package pkg) {
24210        if (!pkg.canHaveOatDir()) {
24211            return null;
24212        }
24213        File codePath = new File(pkg.codePath);
24214        if (codePath.isDirectory()) {
24215            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
24216        }
24217        return null;
24218    }
24219
24220    void deleteOatArtifactsOfPackage(String packageName) {
24221        final String[] instructionSets;
24222        final List<String> codePaths;
24223        final String oatDir;
24224        final PackageParser.Package pkg;
24225        synchronized (mPackages) {
24226            pkg = mPackages.get(packageName);
24227        }
24228        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
24229        codePaths = pkg.getAllCodePaths();
24230        oatDir = getOatDir(pkg);
24231
24232        for (String codePath : codePaths) {
24233            for (String isa : instructionSets) {
24234                try {
24235                    mInstaller.deleteOdex(codePath, isa, oatDir);
24236                } catch (InstallerException e) {
24237                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24238                }
24239            }
24240        }
24241    }
24242
24243    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24244        Set<String> unusedPackages = new HashSet<>();
24245        long currentTimeInMillis = System.currentTimeMillis();
24246        synchronized (mPackages) {
24247            for (PackageParser.Package pkg : mPackages.values()) {
24248                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24249                if (ps == null) {
24250                    continue;
24251                }
24252                PackageDexUsage.PackageUseInfo packageUseInfo =
24253                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24254                if (PackageManagerServiceUtils
24255                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24256                                downgradeTimeThresholdMillis, packageUseInfo,
24257                                pkg.getLatestPackageUseTimeInMills(),
24258                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24259                    unusedPackages.add(pkg.packageName);
24260                }
24261            }
24262        }
24263        return unusedPackages;
24264    }
24265}
24266
24267interface PackageSender {
24268    void sendPackageBroadcast(final String action, final String pkg,
24269        final Bundle extras, final int flags, final String targetPkg,
24270        final IIntentReceiver finishedReceiver, final int[] userIds);
24271    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24272        boolean includeStopped, int appId, int... userIds);
24273}
24274