PackageManagerService.java revision 87505bb58a49768703fde504b7eb4a40429d7721
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
22import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
23import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
25import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
31import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
39import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
55import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
56import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
57import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
58import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
59import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
66import static android.content.pm.PackageManager.MATCH_ALL;
67import static android.content.pm.PackageManager.MATCH_ANY_USER;
68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
83import static android.content.pm.PackageManager.PERMISSION_DENIED;
84import static android.content.pm.PackageManager.PERMISSION_GRANTED;
85import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
86import static android.content.pm.PackageParser.isApkFile;
87import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
88import static android.system.OsConstants.O_CREAT;
89import static android.system.OsConstants.O_RDWR;
90
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
93import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
94import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
95import static com.android.internal.util.ArrayUtils.appendInt;
96import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
99import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
100import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
102import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
105import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
106
107import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
108
109import android.Manifest;
110import android.annotation.IntDef;
111import android.annotation.NonNull;
112import android.annotation.Nullable;
113import android.app.ActivityManager;
114import android.app.AppOpsManager;
115import android.app.IActivityManager;
116import android.app.ResourcesManager;
117import android.app.admin.IDevicePolicyManager;
118import android.app.admin.SecurityLog;
119import android.app.backup.IBackupManager;
120import android.content.BroadcastReceiver;
121import android.content.ComponentName;
122import android.content.ContentResolver;
123import android.content.Context;
124import android.content.IIntentReceiver;
125import android.content.Intent;
126import android.content.IntentFilter;
127import android.content.IntentSender;
128import android.content.IntentSender.SendIntentException;
129import android.content.ServiceConnection;
130import android.content.pm.ActivityInfo;
131import android.content.pm.ApplicationInfo;
132import android.content.pm.AppsQueryHelper;
133import android.content.pm.AuxiliaryResolveInfo;
134import android.content.pm.ChangedPackages;
135import android.content.pm.ComponentInfo;
136import android.content.pm.FallbackCategoryProvider;
137import android.content.pm.FeatureInfo;
138import android.content.pm.IDexModuleRegisterCallback;
139import android.content.pm.IOnPermissionsChangeListener;
140import android.content.pm.IPackageDataObserver;
141import android.content.pm.IPackageDeleteObserver;
142import android.content.pm.IPackageDeleteObserver2;
143import android.content.pm.IPackageInstallObserver2;
144import android.content.pm.IPackageInstaller;
145import android.content.pm.IPackageManager;
146import android.content.pm.IPackageManagerNative;
147import android.content.pm.IPackageMoveObserver;
148import android.content.pm.IPackageStatsObserver;
149import android.content.pm.InstantAppInfo;
150import android.content.pm.InstantAppRequest;
151import android.content.pm.InstantAppResolveInfo;
152import android.content.pm.InstrumentationInfo;
153import android.content.pm.IntentFilterVerificationInfo;
154import android.content.pm.KeySet;
155import android.content.pm.PackageCleanItem;
156import android.content.pm.PackageInfo;
157import android.content.pm.PackageInfoLite;
158import android.content.pm.PackageInstaller;
159import android.content.pm.PackageManager;
160import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
161import android.content.pm.PackageManagerInternal;
162import android.content.pm.PackageParser;
163import android.content.pm.PackageParser.ActivityIntentInfo;
164import android.content.pm.PackageParser.PackageLite;
165import android.content.pm.PackageParser.PackageParserException;
166import android.content.pm.PackageStats;
167import android.content.pm.PackageUserState;
168import android.content.pm.ParceledListSlice;
169import android.content.pm.PermissionGroupInfo;
170import android.content.pm.PermissionInfo;
171import android.content.pm.ProviderInfo;
172import android.content.pm.ResolveInfo;
173import android.content.pm.ServiceInfo;
174import android.content.pm.SharedLibraryInfo;
175import android.content.pm.Signature;
176import android.content.pm.UserInfo;
177import android.content.pm.VerifierDeviceIdentity;
178import android.content.pm.VerifierInfo;
179import android.content.pm.VersionedPackage;
180import android.content.res.Resources;
181import android.database.ContentObserver;
182import android.graphics.Bitmap;
183import android.hardware.display.DisplayManager;
184import android.net.Uri;
185import android.os.Binder;
186import android.os.Build;
187import android.os.Bundle;
188import android.os.Debug;
189import android.os.Environment;
190import android.os.Environment.UserEnvironment;
191import android.os.FileUtils;
192import android.os.Handler;
193import android.os.IBinder;
194import android.os.Looper;
195import android.os.Message;
196import android.os.Parcel;
197import android.os.ParcelFileDescriptor;
198import android.os.PatternMatcher;
199import android.os.Process;
200import android.os.RemoteCallbackList;
201import android.os.RemoteException;
202import android.os.ResultReceiver;
203import android.os.SELinux;
204import android.os.ServiceManager;
205import android.os.ShellCallback;
206import android.os.SystemClock;
207import android.os.SystemProperties;
208import android.os.Trace;
209import android.os.UserHandle;
210import android.os.UserManager;
211import android.os.UserManagerInternal;
212import android.os.storage.IStorageManager;
213import android.os.storage.StorageEventListener;
214import android.os.storage.StorageManager;
215import android.os.storage.StorageManagerInternal;
216import android.os.storage.VolumeInfo;
217import android.os.storage.VolumeRecord;
218import android.provider.Settings.Global;
219import android.provider.Settings.Secure;
220import android.security.KeyStore;
221import android.security.SystemKeyStore;
222import android.service.pm.PackageServiceDumpProto;
223import android.system.ErrnoException;
224import android.system.Os;
225import android.text.TextUtils;
226import android.text.format.DateUtils;
227import android.util.ArrayMap;
228import android.util.ArraySet;
229import android.util.Base64;
230import android.util.BootTimingsTraceLog;
231import android.util.DisplayMetrics;
232import android.util.EventLog;
233import android.util.ExceptionUtils;
234import android.util.Log;
235import android.util.LogPrinter;
236import android.util.MathUtils;
237import android.util.PackageUtils;
238import android.util.Pair;
239import android.util.PrintStreamPrinter;
240import android.util.Slog;
241import android.util.SparseArray;
242import android.util.SparseBooleanArray;
243import android.util.SparseIntArray;
244import android.util.Xml;
245import android.util.jar.StrictJarFile;
246import android.util.proto.ProtoOutputStream;
247import android.view.Display;
248
249import com.android.internal.R;
250import com.android.internal.annotations.GuardedBy;
251import com.android.internal.app.IMediaContainerService;
252import com.android.internal.app.ResolverActivity;
253import com.android.internal.content.NativeLibraryHelper;
254import com.android.internal.content.PackageHelper;
255import com.android.internal.logging.MetricsLogger;
256import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
257import com.android.internal.os.IParcelFileDescriptorFactory;
258import com.android.internal.os.RoSystemProperties;
259import com.android.internal.os.SomeArgs;
260import com.android.internal.os.Zygote;
261import com.android.internal.telephony.CarrierAppUtils;
262import com.android.internal.util.ArrayUtils;
263import com.android.internal.util.ConcurrentUtils;
264import com.android.internal.util.DumpUtils;
265import com.android.internal.util.FastPrintWriter;
266import com.android.internal.util.FastXmlSerializer;
267import com.android.internal.util.IndentingPrintWriter;
268import com.android.internal.util.Preconditions;
269import com.android.internal.util.XmlUtils;
270import com.android.server.AttributeCache;
271import com.android.server.DeviceIdleController;
272import com.android.server.EventLogTags;
273import com.android.server.FgThread;
274import com.android.server.IntentResolver;
275import com.android.server.LocalServices;
276import com.android.server.LockGuard;
277import com.android.server.ServiceThread;
278import com.android.server.SystemConfig;
279import com.android.server.SystemServerInitThreadPool;
280import com.android.server.Watchdog;
281import com.android.server.net.NetworkPolicyManagerInternal;
282import com.android.server.pm.Installer.InstallerException;
283import com.android.server.pm.PermissionsState.PermissionState;
284import com.android.server.pm.Settings.DatabaseVersion;
285import com.android.server.pm.Settings.VersionInfo;
286import com.android.server.pm.dex.DexManager;
287import com.android.server.pm.dex.DexoptOptions;
288import com.android.server.pm.dex.PackageDexUsage;
289import com.android.server.storage.DeviceStorageMonitorInternal;
290
291import dalvik.system.CloseGuard;
292import dalvik.system.DexFile;
293import dalvik.system.VMRuntime;
294
295import libcore.io.IoUtils;
296import libcore.io.Streams;
297import libcore.util.EmptyArray;
298
299import org.xmlpull.v1.XmlPullParser;
300import org.xmlpull.v1.XmlPullParserException;
301import org.xmlpull.v1.XmlSerializer;
302
303import java.io.BufferedOutputStream;
304import java.io.BufferedReader;
305import java.io.ByteArrayInputStream;
306import java.io.ByteArrayOutputStream;
307import java.io.File;
308import java.io.FileDescriptor;
309import java.io.FileInputStream;
310import java.io.FileOutputStream;
311import java.io.FileReader;
312import java.io.FilenameFilter;
313import java.io.IOException;
314import java.io.InputStream;
315import java.io.OutputStream;
316import java.io.PrintWriter;
317import java.lang.annotation.Retention;
318import java.lang.annotation.RetentionPolicy;
319import java.nio.charset.StandardCharsets;
320import java.security.DigestInputStream;
321import java.security.MessageDigest;
322import java.security.NoSuchAlgorithmException;
323import java.security.PublicKey;
324import java.security.SecureRandom;
325import java.security.cert.Certificate;
326import java.security.cert.CertificateEncodingException;
327import java.security.cert.CertificateException;
328import java.text.SimpleDateFormat;
329import java.util.ArrayList;
330import java.util.Arrays;
331import java.util.Collection;
332import java.util.Collections;
333import java.util.Comparator;
334import java.util.Date;
335import java.util.HashMap;
336import java.util.HashSet;
337import java.util.Iterator;
338import java.util.List;
339import java.util.Map;
340import java.util.Objects;
341import java.util.Set;
342import java.util.concurrent.CountDownLatch;
343import java.util.concurrent.Future;
344import java.util.concurrent.TimeUnit;
345import java.util.concurrent.atomic.AtomicBoolean;
346import java.util.concurrent.atomic.AtomicInteger;
347import java.util.zip.GZIPInputStream;
348
349/**
350 * Keep track of all those APKs everywhere.
351 * <p>
352 * Internally there are two important locks:
353 * <ul>
354 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
355 * and other related state. It is a fine-grained lock that should only be held
356 * momentarily, as it's one of the most contended locks in the system.
357 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
358 * operations typically involve heavy lifting of application data on disk. Since
359 * {@code installd} is single-threaded, and it's operations can often be slow,
360 * this lock should never be acquired while already holding {@link #mPackages}.
361 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
362 * holding {@link #mInstallLock}.
363 * </ul>
364 * Many internal methods rely on the caller to hold the appropriate locks, and
365 * this contract is expressed through method name suffixes:
366 * <ul>
367 * <li>fooLI(): the caller must hold {@link #mInstallLock}
368 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
369 * being modified must be frozen
370 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
371 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
372 * </ul>
373 * <p>
374 * Because this class is very central to the platform's security; please run all
375 * CTS and unit tests whenever making modifications:
376 *
377 * <pre>
378 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
379 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
380 * </pre>
381 */
382public class PackageManagerService extends IPackageManager.Stub
383        implements PackageSender {
384    static final String TAG = "PackageManager";
385    static final boolean DEBUG_SETTINGS = false;
386    static final boolean DEBUG_PREFERRED = false;
387    static final boolean DEBUG_UPGRADE = false;
388    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
389    private static final boolean DEBUG_BACKUP = false;
390    private static final boolean DEBUG_INSTALL = false;
391    private static final boolean DEBUG_REMOVE = false;
392    private static final boolean DEBUG_BROADCASTS = false;
393    private static final boolean DEBUG_SHOW_INFO = false;
394    private static final boolean DEBUG_PACKAGE_INFO = false;
395    private static final boolean DEBUG_INTENT_MATCHING = false;
396    private static final boolean DEBUG_PACKAGE_SCANNING = false;
397    private static final boolean DEBUG_VERIFY = false;
398    private static final boolean DEBUG_FILTERS = false;
399    private static final boolean DEBUG_PERMISSIONS = false;
400    private static final boolean DEBUG_SHARED_LIBRARIES = false;
401    private static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
402
403    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
404    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
405    // user, but by default initialize to this.
406    public static final boolean DEBUG_DEXOPT = false;
407
408    private static final boolean DEBUG_ABI_SELECTION = false;
409    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
410    private static final boolean DEBUG_TRIAGED_MISSING = false;
411    private static final boolean DEBUG_APP_DATA = false;
412
413    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
414    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
415
416    private static final boolean HIDE_EPHEMERAL_APIS = false;
417
418    private static final boolean ENABLE_FREE_CACHE_V2 =
419            SystemProperties.getBoolean("fw.free_cache_v2", true);
420
421    private static final int RADIO_UID = Process.PHONE_UID;
422    private static final int LOG_UID = Process.LOG_UID;
423    private static final int NFC_UID = Process.NFC_UID;
424    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
425    private static final int SHELL_UID = Process.SHELL_UID;
426
427    // Cap the size of permission trees that 3rd party apps can define
428    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
429
430    // Suffix used during package installation when copying/moving
431    // package apks to install directory.
432    private static final String INSTALL_PACKAGE_SUFFIX = "-";
433
434    static final int SCAN_NO_DEX = 1<<1;
435    static final int SCAN_FORCE_DEX = 1<<2;
436    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
437    static final int SCAN_NEW_INSTALL = 1<<4;
438    static final int SCAN_UPDATE_TIME = 1<<5;
439    static final int SCAN_BOOTING = 1<<6;
440    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
441    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
442    static final int SCAN_REPLACING = 1<<9;
443    static final int SCAN_REQUIRE_KNOWN = 1<<10;
444    static final int SCAN_MOVE = 1<<11;
445    static final int SCAN_INITIAL = 1<<12;
446    static final int SCAN_CHECK_ONLY = 1<<13;
447    static final int SCAN_DONT_KILL_APP = 1<<14;
448    static final int SCAN_IGNORE_FROZEN = 1<<15;
449    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
450    static final int SCAN_AS_INSTANT_APP = 1<<17;
451    static final int SCAN_AS_FULL_APP = 1<<18;
452    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<19;
453    /** Should not be with the scan flags */
454    static final int FLAGS_REMOVE_CHATTY = 1<<31;
455
456    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
457    /** Extension of the compressed packages */
458    private final static String COMPRESSED_EXTENSION = ".gz";
459
460    private static final int[] EMPTY_INT_ARRAY = new int[0];
461
462    private static final int TYPE_UNKNOWN = 0;
463    private static final int TYPE_ACTIVITY = 1;
464    private static final int TYPE_RECEIVER = 2;
465    private static final int TYPE_SERVICE = 3;
466    private static final int TYPE_PROVIDER = 4;
467    @IntDef(prefix = { "TYPE_" }, value = {
468            TYPE_UNKNOWN,
469            TYPE_ACTIVITY,
470            TYPE_RECEIVER,
471            TYPE_SERVICE,
472            TYPE_PROVIDER,
473    })
474    @Retention(RetentionPolicy.SOURCE)
475    public @interface ComponentType {}
476
477    /**
478     * Timeout (in milliseconds) after which the watchdog should declare that
479     * our handler thread is wedged.  The usual default for such things is one
480     * minute but we sometimes do very lengthy I/O operations on this thread,
481     * such as installing multi-gigabyte applications, so ours needs to be longer.
482     */
483    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
484
485    /**
486     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
487     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
488     * settings entry if available, otherwise we use the hardcoded default.  If it's been
489     * more than this long since the last fstrim, we force one during the boot sequence.
490     *
491     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
492     * one gets run at the next available charging+idle time.  This final mandatory
493     * no-fstrim check kicks in only of the other scheduling criteria is never met.
494     */
495    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
496
497    /**
498     * Whether verification is enabled by default.
499     */
500    private static final boolean DEFAULT_VERIFY_ENABLE = true;
501
502    /**
503     * The default maximum time to wait for the verification agent to return in
504     * milliseconds.
505     */
506    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
507
508    /**
509     * The default response for package verification timeout.
510     *
511     * This can be either PackageManager.VERIFICATION_ALLOW or
512     * PackageManager.VERIFICATION_REJECT.
513     */
514    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
515
516    static final String PLATFORM_PACKAGE_NAME = "android";
517
518    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
519
520    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
521            DEFAULT_CONTAINER_PACKAGE,
522            "com.android.defcontainer.DefaultContainerService");
523
524    private static final String KILL_APP_REASON_GIDS_CHANGED =
525            "permission grant or revoke changed gids";
526
527    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
528            "permissions revoked";
529
530    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
531
532    private static final String PACKAGE_SCHEME = "package";
533
534    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
535
536    /** Permission grant: not grant the permission. */
537    private static final int GRANT_DENIED = 1;
538
539    /** Permission grant: grant the permission as an install permission. */
540    private static final int GRANT_INSTALL = 2;
541
542    /** Permission grant: grant the permission as a runtime one. */
543    private static final int GRANT_RUNTIME = 3;
544
545    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
546    private static final int GRANT_UPGRADE = 4;
547
548    /** Canonical intent used to identify what counts as a "web browser" app */
549    private static final Intent sBrowserIntent;
550    static {
551        sBrowserIntent = new Intent();
552        sBrowserIntent.setAction(Intent.ACTION_VIEW);
553        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
554        sBrowserIntent.setData(Uri.parse("http:"));
555    }
556
557    /**
558     * The set of all protected actions [i.e. those actions for which a high priority
559     * intent filter is disallowed].
560     */
561    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
562    static {
563        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
564        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
565        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
566        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
567    }
568
569    // Compilation reasons.
570    public static final int REASON_FIRST_BOOT = 0;
571    public static final int REASON_BOOT = 1;
572    public static final int REASON_INSTALL = 2;
573    public static final int REASON_BACKGROUND_DEXOPT = 3;
574    public static final int REASON_AB_OTA = 4;
575    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
576
577    public static final int REASON_LAST = REASON_INACTIVE_PACKAGE_DOWNGRADE;
578
579    /** All dangerous permission names in the same order as the events in MetricsEvent */
580    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
581            Manifest.permission.READ_CALENDAR,
582            Manifest.permission.WRITE_CALENDAR,
583            Manifest.permission.CAMERA,
584            Manifest.permission.READ_CONTACTS,
585            Manifest.permission.WRITE_CONTACTS,
586            Manifest.permission.GET_ACCOUNTS,
587            Manifest.permission.ACCESS_FINE_LOCATION,
588            Manifest.permission.ACCESS_COARSE_LOCATION,
589            Manifest.permission.RECORD_AUDIO,
590            Manifest.permission.READ_PHONE_STATE,
591            Manifest.permission.CALL_PHONE,
592            Manifest.permission.READ_CALL_LOG,
593            Manifest.permission.WRITE_CALL_LOG,
594            Manifest.permission.ADD_VOICEMAIL,
595            Manifest.permission.USE_SIP,
596            Manifest.permission.PROCESS_OUTGOING_CALLS,
597            Manifest.permission.READ_CELL_BROADCASTS,
598            Manifest.permission.BODY_SENSORS,
599            Manifest.permission.SEND_SMS,
600            Manifest.permission.RECEIVE_SMS,
601            Manifest.permission.READ_SMS,
602            Manifest.permission.RECEIVE_WAP_PUSH,
603            Manifest.permission.RECEIVE_MMS,
604            Manifest.permission.READ_EXTERNAL_STORAGE,
605            Manifest.permission.WRITE_EXTERNAL_STORAGE,
606            Manifest.permission.READ_PHONE_NUMBERS,
607            Manifest.permission.ANSWER_PHONE_CALLS);
608
609
610    /**
611     * Version number for the package parser cache. Increment this whenever the format or
612     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
613     */
614    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
615
616    /**
617     * Whether the package parser cache is enabled.
618     */
619    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
620
621    final ServiceThread mHandlerThread;
622
623    final PackageHandler mHandler;
624
625    private final ProcessLoggingHandler mProcessLoggingHandler;
626
627    /**
628     * Messages for {@link #mHandler} that need to wait for system ready before
629     * being dispatched.
630     */
631    private ArrayList<Message> mPostSystemReadyMessages;
632
633    final int mSdkVersion = Build.VERSION.SDK_INT;
634
635    final Context mContext;
636    final boolean mFactoryTest;
637    final boolean mOnlyCore;
638    final DisplayMetrics mMetrics;
639    final int mDefParseFlags;
640    final String[] mSeparateProcesses;
641    final boolean mIsUpgrade;
642    final boolean mIsPreNUpgrade;
643    final boolean mIsPreNMR1Upgrade;
644
645    // Have we told the Activity Manager to whitelist the default container service by uid yet?
646    @GuardedBy("mPackages")
647    boolean mDefaultContainerWhitelisted = false;
648
649    @GuardedBy("mPackages")
650    private boolean mDexOptDialogShown;
651
652    /** The location for ASEC container files on internal storage. */
653    final String mAsecInternalPath;
654
655    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
656    // LOCK HELD.  Can be called with mInstallLock held.
657    @GuardedBy("mInstallLock")
658    final Installer mInstaller;
659
660    /** Directory where installed third-party apps stored */
661    final File mAppInstallDir;
662
663    /**
664     * Directory to which applications installed internally have their
665     * 32 bit native libraries copied.
666     */
667    private File mAppLib32InstallDir;
668
669    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
670    // apps.
671    final File mDrmAppPrivateInstallDir;
672
673    // ----------------------------------------------------------------
674
675    // Lock for state used when installing and doing other long running
676    // operations.  Methods that must be called with this lock held have
677    // the suffix "LI".
678    final Object mInstallLock = new Object();
679
680    // ----------------------------------------------------------------
681
682    // Keys are String (package name), values are Package.  This also serves
683    // as the lock for the global state.  Methods that must be called with
684    // this lock held have the prefix "LP".
685    @GuardedBy("mPackages")
686    final ArrayMap<String, PackageParser.Package> mPackages =
687            new ArrayMap<String, PackageParser.Package>();
688
689    final ArrayMap<String, Set<String>> mKnownCodebase =
690            new ArrayMap<String, Set<String>>();
691
692    // Keys are isolated uids and values are the uid of the application
693    // that created the isolated proccess.
694    @GuardedBy("mPackages")
695    final SparseIntArray mIsolatedOwners = new SparseIntArray();
696
697    /**
698     * Tracks new system packages [received in an OTA] that we expect to
699     * find updated user-installed versions. Keys are package name, values
700     * are package location.
701     */
702    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
703    /**
704     * Tracks high priority intent filters for protected actions. During boot, certain
705     * filter actions are protected and should never be allowed to have a high priority
706     * intent filter for them. However, there is one, and only one exception -- the
707     * setup wizard. It must be able to define a high priority intent filter for these
708     * actions to ensure there are no escapes from the wizard. We need to delay processing
709     * of these during boot as we need to look at all of the system packages in order
710     * to know which component is the setup wizard.
711     */
712    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
713    /**
714     * Whether or not processing protected filters should be deferred.
715     */
716    private boolean mDeferProtectedFilters = true;
717
718    /**
719     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
720     */
721    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
722    /**
723     * Whether or not system app permissions should be promoted from install to runtime.
724     */
725    boolean mPromoteSystemApps;
726
727    @GuardedBy("mPackages")
728    final Settings mSettings;
729
730    /**
731     * Set of package names that are currently "frozen", which means active
732     * surgery is being done on the code/data for that package. The platform
733     * will refuse to launch frozen packages to avoid race conditions.
734     *
735     * @see PackageFreezer
736     */
737    @GuardedBy("mPackages")
738    final ArraySet<String> mFrozenPackages = new ArraySet<>();
739
740    final ProtectedPackages mProtectedPackages;
741
742    @GuardedBy("mLoadedVolumes")
743    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
744
745    boolean mFirstBoot;
746
747    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
748
749    // System configuration read by SystemConfig.
750    final int[] mGlobalGids;
751    final SparseArray<ArraySet<String>> mSystemPermissions;
752    @GuardedBy("mAvailableFeatures")
753    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
754
755    // If mac_permissions.xml was found for seinfo labeling.
756    boolean mFoundPolicyFile;
757
758    private final InstantAppRegistry mInstantAppRegistry;
759
760    @GuardedBy("mPackages")
761    int mChangedPackagesSequenceNumber;
762    /**
763     * List of changed [installed, removed or updated] packages.
764     * mapping from user id -> sequence number -> package name
765     */
766    @GuardedBy("mPackages")
767    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
768    /**
769     * The sequence number of the last change to a package.
770     * mapping from user id -> package name -> sequence number
771     */
772    @GuardedBy("mPackages")
773    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
774
775    class PackageParserCallback implements PackageParser.Callback {
776        @Override public final boolean hasFeature(String feature) {
777            return PackageManagerService.this.hasSystemFeature(feature, 0);
778        }
779
780        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
781                Collection<PackageParser.Package> allPackages, String targetPackageName) {
782            List<PackageParser.Package> overlayPackages = null;
783            for (PackageParser.Package p : allPackages) {
784                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
785                    if (overlayPackages == null) {
786                        overlayPackages = new ArrayList<PackageParser.Package>();
787                    }
788                    overlayPackages.add(p);
789                }
790            }
791            if (overlayPackages != null) {
792                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
793                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
794                        return p1.mOverlayPriority - p2.mOverlayPriority;
795                    }
796                };
797                Collections.sort(overlayPackages, cmp);
798            }
799            return overlayPackages;
800        }
801
802        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
803                String targetPackageName, String targetPath) {
804            if ("android".equals(targetPackageName)) {
805                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
806                // native AssetManager.
807                return null;
808            }
809            List<PackageParser.Package> overlayPackages =
810                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
811            if (overlayPackages == null || overlayPackages.isEmpty()) {
812                return null;
813            }
814            List<String> overlayPathList = null;
815            for (PackageParser.Package overlayPackage : overlayPackages) {
816                if (targetPath == null) {
817                    if (overlayPathList == null) {
818                        overlayPathList = new ArrayList<String>();
819                    }
820                    overlayPathList.add(overlayPackage.baseCodePath);
821                    continue;
822                }
823
824                try {
825                    // Creates idmaps for system to parse correctly the Android manifest of the
826                    // target package.
827                    //
828                    // OverlayManagerService will update each of them with a correct gid from its
829                    // target package app id.
830                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
831                            UserHandle.getSharedAppGid(
832                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
833                    if (overlayPathList == null) {
834                        overlayPathList = new ArrayList<String>();
835                    }
836                    overlayPathList.add(overlayPackage.baseCodePath);
837                } catch (InstallerException e) {
838                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
839                            overlayPackage.baseCodePath);
840                }
841            }
842            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
843        }
844
845        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
846            synchronized (mPackages) {
847                return getStaticOverlayPathsLocked(
848                        mPackages.values(), targetPackageName, targetPath);
849            }
850        }
851
852        @Override public final String[] getOverlayApks(String targetPackageName) {
853            return getStaticOverlayPaths(targetPackageName, null);
854        }
855
856        @Override public final String[] getOverlayPaths(String targetPackageName,
857                String targetPath) {
858            return getStaticOverlayPaths(targetPackageName, targetPath);
859        }
860    };
861
862    class ParallelPackageParserCallback extends PackageParserCallback {
863        List<PackageParser.Package> mOverlayPackages = null;
864
865        void findStaticOverlayPackages() {
866            synchronized (mPackages) {
867                for (PackageParser.Package p : mPackages.values()) {
868                    if (p.mIsStaticOverlay) {
869                        if (mOverlayPackages == null) {
870                            mOverlayPackages = new ArrayList<PackageParser.Package>();
871                        }
872                        mOverlayPackages.add(p);
873                    }
874                }
875            }
876        }
877
878        @Override
879        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
880            // We can trust mOverlayPackages without holding mPackages because package uninstall
881            // can't happen while running parallel parsing.
882            // Moreover holding mPackages on each parsing thread causes dead-lock.
883            return mOverlayPackages == null ? null :
884                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
885        }
886    }
887
888    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
889    final ParallelPackageParserCallback mParallelPackageParserCallback =
890            new ParallelPackageParserCallback();
891
892    public static final class SharedLibraryEntry {
893        public final @Nullable String path;
894        public final @Nullable String apk;
895        public final @NonNull SharedLibraryInfo info;
896
897        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
898                String declaringPackageName, int declaringPackageVersionCode) {
899            path = _path;
900            apk = _apk;
901            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
902                    declaringPackageName, declaringPackageVersionCode), null);
903        }
904    }
905
906    // Currently known shared libraries.
907    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
908    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
909            new ArrayMap<>();
910
911    // All available activities, for your resolving pleasure.
912    final ActivityIntentResolver mActivities =
913            new ActivityIntentResolver();
914
915    // All available receivers, for your resolving pleasure.
916    final ActivityIntentResolver mReceivers =
917            new ActivityIntentResolver();
918
919    // All available services, for your resolving pleasure.
920    final ServiceIntentResolver mServices = new ServiceIntentResolver();
921
922    // All available providers, for your resolving pleasure.
923    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
924
925    // Mapping from provider base names (first directory in content URI codePath)
926    // to the provider information.
927    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
928            new ArrayMap<String, PackageParser.Provider>();
929
930    // Mapping from instrumentation class names to info about them.
931    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
932            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
933
934    // Mapping from permission names to info about them.
935    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
936            new ArrayMap<String, PackageParser.PermissionGroup>();
937
938    // Packages whose data we have transfered into another package, thus
939    // should no longer exist.
940    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
941
942    // Broadcast actions that are only available to the system.
943    @GuardedBy("mProtectedBroadcasts")
944    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
945
946    /** List of packages waiting for verification. */
947    final SparseArray<PackageVerificationState> mPendingVerification
948            = new SparseArray<PackageVerificationState>();
949
950    /** Set of packages associated with each app op permission. */
951    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
952
953    final PackageInstallerService mInstallerService;
954
955    private final PackageDexOptimizer mPackageDexOptimizer;
956    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
957    // is used by other apps).
958    private final DexManager mDexManager;
959
960    private AtomicInteger mNextMoveId = new AtomicInteger();
961    private final MoveCallbacks mMoveCallbacks;
962
963    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
964
965    // Cache of users who need badging.
966    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
967
968    /** Token for keys in mPendingVerification. */
969    private int mPendingVerificationToken = 0;
970
971    volatile boolean mSystemReady;
972    volatile boolean mSafeMode;
973    volatile boolean mHasSystemUidErrors;
974    private volatile boolean mEphemeralAppsDisabled;
975
976    ApplicationInfo mAndroidApplication;
977    final ActivityInfo mResolveActivity = new ActivityInfo();
978    final ResolveInfo mResolveInfo = new ResolveInfo();
979    ComponentName mResolveComponentName;
980    PackageParser.Package mPlatformPackage;
981    ComponentName mCustomResolverComponentName;
982
983    boolean mResolverReplaced = false;
984
985    private final @Nullable ComponentName mIntentFilterVerifierComponent;
986    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
987
988    private int mIntentFilterVerificationToken = 0;
989
990    /** The service connection to the ephemeral resolver */
991    final EphemeralResolverConnection mInstantAppResolverConnection;
992    /** Component used to show resolver settings for Instant Apps */
993    final ComponentName mInstantAppResolverSettingsComponent;
994
995    /** Activity used to install instant applications */
996    ActivityInfo mInstantAppInstallerActivity;
997    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
998
999    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
1000            = new SparseArray<IntentFilterVerificationState>();
1001
1002    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1003
1004    // List of packages names to keep cached, even if they are uninstalled for all users
1005    private List<String> mKeepUninstalledPackages;
1006
1007    private UserManagerInternal mUserManagerInternal;
1008
1009    private DeviceIdleController.LocalService mDeviceIdleController;
1010
1011    private File mCacheDir;
1012
1013    private ArraySet<String> mPrivappPermissionsViolations;
1014
1015    private Future<?> mPrepareAppDataFuture;
1016
1017    private static class IFVerificationParams {
1018        PackageParser.Package pkg;
1019        boolean replacing;
1020        int userId;
1021        int verifierUid;
1022
1023        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1024                int _userId, int _verifierUid) {
1025            pkg = _pkg;
1026            replacing = _replacing;
1027            userId = _userId;
1028            replacing = _replacing;
1029            verifierUid = _verifierUid;
1030        }
1031    }
1032
1033    private interface IntentFilterVerifier<T extends IntentFilter> {
1034        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1035                                               T filter, String packageName);
1036        void startVerifications(int userId);
1037        void receiveVerificationResponse(int verificationId);
1038    }
1039
1040    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1041        private Context mContext;
1042        private ComponentName mIntentFilterVerifierComponent;
1043        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1044
1045        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1046            mContext = context;
1047            mIntentFilterVerifierComponent = verifierComponent;
1048        }
1049
1050        private String getDefaultScheme() {
1051            return IntentFilter.SCHEME_HTTPS;
1052        }
1053
1054        @Override
1055        public void startVerifications(int userId) {
1056            // Launch verifications requests
1057            int count = mCurrentIntentFilterVerifications.size();
1058            for (int n=0; n<count; n++) {
1059                int verificationId = mCurrentIntentFilterVerifications.get(n);
1060                final IntentFilterVerificationState ivs =
1061                        mIntentFilterVerificationStates.get(verificationId);
1062
1063                String packageName = ivs.getPackageName();
1064
1065                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1066                final int filterCount = filters.size();
1067                ArraySet<String> domainsSet = new ArraySet<>();
1068                for (int m=0; m<filterCount; m++) {
1069                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1070                    domainsSet.addAll(filter.getHostsList());
1071                }
1072                synchronized (mPackages) {
1073                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1074                            packageName, domainsSet) != null) {
1075                        scheduleWriteSettingsLocked();
1076                    }
1077                }
1078                sendVerificationRequest(verificationId, ivs);
1079            }
1080            mCurrentIntentFilterVerifications.clear();
1081        }
1082
1083        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1084            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1085            verificationIntent.putExtra(
1086                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1087                    verificationId);
1088            verificationIntent.putExtra(
1089                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1090                    getDefaultScheme());
1091            verificationIntent.putExtra(
1092                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1093                    ivs.getHostsString());
1094            verificationIntent.putExtra(
1095                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1096                    ivs.getPackageName());
1097            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1098            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1099
1100            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1101            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1102                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1103                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1104
1105            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1106            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1107                    "Sending IntentFilter verification broadcast");
1108        }
1109
1110        public void receiveVerificationResponse(int verificationId) {
1111            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1112
1113            final boolean verified = ivs.isVerified();
1114
1115            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1116            final int count = filters.size();
1117            if (DEBUG_DOMAIN_VERIFICATION) {
1118                Slog.i(TAG, "Received verification response " + verificationId
1119                        + " for " + count + " filters, verified=" + verified);
1120            }
1121            for (int n=0; n<count; n++) {
1122                PackageParser.ActivityIntentInfo filter = filters.get(n);
1123                filter.setVerified(verified);
1124
1125                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1126                        + " verified with result:" + verified + " and hosts:"
1127                        + ivs.getHostsString());
1128            }
1129
1130            mIntentFilterVerificationStates.remove(verificationId);
1131
1132            final String packageName = ivs.getPackageName();
1133            IntentFilterVerificationInfo ivi = null;
1134
1135            synchronized (mPackages) {
1136                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1137            }
1138            if (ivi == null) {
1139                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1140                        + verificationId + " packageName:" + packageName);
1141                return;
1142            }
1143            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1144                    "Updating IntentFilterVerificationInfo for package " + packageName
1145                            +" verificationId:" + verificationId);
1146
1147            synchronized (mPackages) {
1148                if (verified) {
1149                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1150                } else {
1151                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1152                }
1153                scheduleWriteSettingsLocked();
1154
1155                final int userId = ivs.getUserId();
1156                if (userId != UserHandle.USER_ALL) {
1157                    final int userStatus =
1158                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1159
1160                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1161                    boolean needUpdate = false;
1162
1163                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1164                    // already been set by the User thru the Disambiguation dialog
1165                    switch (userStatus) {
1166                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1167                            if (verified) {
1168                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1169                            } else {
1170                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1171                            }
1172                            needUpdate = true;
1173                            break;
1174
1175                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1176                            if (verified) {
1177                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1178                                needUpdate = true;
1179                            }
1180                            break;
1181
1182                        default:
1183                            // Nothing to do
1184                    }
1185
1186                    if (needUpdate) {
1187                        mSettings.updateIntentFilterVerificationStatusLPw(
1188                                packageName, updatedStatus, userId);
1189                        scheduleWritePackageRestrictionsLocked(userId);
1190                    }
1191                }
1192            }
1193        }
1194
1195        @Override
1196        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1197                    ActivityIntentInfo filter, String packageName) {
1198            if (!hasValidDomains(filter)) {
1199                return false;
1200            }
1201            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1202            if (ivs == null) {
1203                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1204                        packageName);
1205            }
1206            if (DEBUG_DOMAIN_VERIFICATION) {
1207                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1208            }
1209            ivs.addFilter(filter);
1210            return true;
1211        }
1212
1213        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1214                int userId, int verificationId, String packageName) {
1215            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1216                    verifierUid, userId, packageName);
1217            ivs.setPendingState();
1218            synchronized (mPackages) {
1219                mIntentFilterVerificationStates.append(verificationId, ivs);
1220                mCurrentIntentFilterVerifications.add(verificationId);
1221            }
1222            return ivs;
1223        }
1224    }
1225
1226    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1227        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1228                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1229                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1230    }
1231
1232    // Set of pending broadcasts for aggregating enable/disable of components.
1233    static class PendingPackageBroadcasts {
1234        // for each user id, a map of <package name -> components within that package>
1235        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1236
1237        public PendingPackageBroadcasts() {
1238            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1239        }
1240
1241        public ArrayList<String> get(int userId, String packageName) {
1242            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1243            return packages.get(packageName);
1244        }
1245
1246        public void put(int userId, String packageName, ArrayList<String> components) {
1247            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1248            packages.put(packageName, components);
1249        }
1250
1251        public void remove(int userId, String packageName) {
1252            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1253            if (packages != null) {
1254                packages.remove(packageName);
1255            }
1256        }
1257
1258        public void remove(int userId) {
1259            mUidMap.remove(userId);
1260        }
1261
1262        public int userIdCount() {
1263            return mUidMap.size();
1264        }
1265
1266        public int userIdAt(int n) {
1267            return mUidMap.keyAt(n);
1268        }
1269
1270        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1271            return mUidMap.get(userId);
1272        }
1273
1274        public int size() {
1275            // total number of pending broadcast entries across all userIds
1276            int num = 0;
1277            for (int i = 0; i< mUidMap.size(); i++) {
1278                num += mUidMap.valueAt(i).size();
1279            }
1280            return num;
1281        }
1282
1283        public void clear() {
1284            mUidMap.clear();
1285        }
1286
1287        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1288            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1289            if (map == null) {
1290                map = new ArrayMap<String, ArrayList<String>>();
1291                mUidMap.put(userId, map);
1292            }
1293            return map;
1294        }
1295    }
1296    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1297
1298    // Service Connection to remote media container service to copy
1299    // package uri's from external media onto secure containers
1300    // or internal storage.
1301    private IMediaContainerService mContainerService = null;
1302
1303    static final int SEND_PENDING_BROADCAST = 1;
1304    static final int MCS_BOUND = 3;
1305    static final int END_COPY = 4;
1306    static final int INIT_COPY = 5;
1307    static final int MCS_UNBIND = 6;
1308    static final int START_CLEANING_PACKAGE = 7;
1309    static final int FIND_INSTALL_LOC = 8;
1310    static final int POST_INSTALL = 9;
1311    static final int MCS_RECONNECT = 10;
1312    static final int MCS_GIVE_UP = 11;
1313    static final int UPDATED_MEDIA_STATUS = 12;
1314    static final int WRITE_SETTINGS = 13;
1315    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1316    static final int PACKAGE_VERIFIED = 15;
1317    static final int CHECK_PENDING_VERIFICATION = 16;
1318    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1319    static final int INTENT_FILTER_VERIFIED = 18;
1320    static final int WRITE_PACKAGE_LIST = 19;
1321    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1322
1323    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1324
1325    // Delay time in millisecs
1326    static final int BROADCAST_DELAY = 10 * 1000;
1327
1328    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1329            2 * 60 * 60 * 1000L; /* two hours */
1330
1331    static UserManagerService sUserManager;
1332
1333    // Stores a list of users whose package restrictions file needs to be updated
1334    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1335
1336    final private DefaultContainerConnection mDefContainerConn =
1337            new DefaultContainerConnection();
1338    class DefaultContainerConnection implements ServiceConnection {
1339        public void onServiceConnected(ComponentName name, IBinder service) {
1340            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1341            final IMediaContainerService imcs = IMediaContainerService.Stub
1342                    .asInterface(Binder.allowBlocking(service));
1343            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1344        }
1345
1346        public void onServiceDisconnected(ComponentName name) {
1347            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1348        }
1349    }
1350
1351    // Recordkeeping of restore-after-install operations that are currently in flight
1352    // between the Package Manager and the Backup Manager
1353    static class PostInstallData {
1354        public InstallArgs args;
1355        public PackageInstalledInfo res;
1356
1357        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1358            args = _a;
1359            res = _r;
1360        }
1361    }
1362
1363    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1364    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1365
1366    // XML tags for backup/restore of various bits of state
1367    private static final String TAG_PREFERRED_BACKUP = "pa";
1368    private static final String TAG_DEFAULT_APPS = "da";
1369    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1370
1371    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1372    private static final String TAG_ALL_GRANTS = "rt-grants";
1373    private static final String TAG_GRANT = "grant";
1374    private static final String ATTR_PACKAGE_NAME = "pkg";
1375
1376    private static final String TAG_PERMISSION = "perm";
1377    private static final String ATTR_PERMISSION_NAME = "name";
1378    private static final String ATTR_IS_GRANTED = "g";
1379    private static final String ATTR_USER_SET = "set";
1380    private static final String ATTR_USER_FIXED = "fixed";
1381    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1382
1383    // System/policy permission grants are not backed up
1384    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1385            FLAG_PERMISSION_POLICY_FIXED
1386            | FLAG_PERMISSION_SYSTEM_FIXED
1387            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1388
1389    // And we back up these user-adjusted states
1390    private static final int USER_RUNTIME_GRANT_MASK =
1391            FLAG_PERMISSION_USER_SET
1392            | FLAG_PERMISSION_USER_FIXED
1393            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1394
1395    final @Nullable String mRequiredVerifierPackage;
1396    final @NonNull String mRequiredInstallerPackage;
1397    final @NonNull String mRequiredUninstallerPackage;
1398    final @Nullable String mSetupWizardPackage;
1399    final @Nullable String mStorageManagerPackage;
1400    final @NonNull String mServicesSystemSharedLibraryPackageName;
1401    final @NonNull String mSharedSystemSharedLibraryPackageName;
1402
1403    final boolean mPermissionReviewRequired;
1404
1405    private final PackageUsage mPackageUsage = new PackageUsage();
1406    private final CompilerStats mCompilerStats = new CompilerStats();
1407
1408    class PackageHandler extends Handler {
1409        private boolean mBound = false;
1410        final ArrayList<HandlerParams> mPendingInstalls =
1411            new ArrayList<HandlerParams>();
1412
1413        private boolean connectToService() {
1414            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1415                    " DefaultContainerService");
1416            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1417            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1418            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1419                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1420                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1421                mBound = true;
1422                return true;
1423            }
1424            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1425            return false;
1426        }
1427
1428        private void disconnectService() {
1429            mContainerService = null;
1430            mBound = false;
1431            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1432            mContext.unbindService(mDefContainerConn);
1433            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1434        }
1435
1436        PackageHandler(Looper looper) {
1437            super(looper);
1438        }
1439
1440        public void handleMessage(Message msg) {
1441            try {
1442                doHandleMessage(msg);
1443            } finally {
1444                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1445            }
1446        }
1447
1448        void doHandleMessage(Message msg) {
1449            switch (msg.what) {
1450                case INIT_COPY: {
1451                    HandlerParams params = (HandlerParams) msg.obj;
1452                    int idx = mPendingInstalls.size();
1453                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1454                    // If a bind was already initiated we dont really
1455                    // need to do anything. The pending install
1456                    // will be processed later on.
1457                    if (!mBound) {
1458                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1459                                System.identityHashCode(mHandler));
1460                        // If this is the only one pending we might
1461                        // have to bind to the service again.
1462                        if (!connectToService()) {
1463                            Slog.e(TAG, "Failed to bind to media container service");
1464                            params.serviceError();
1465                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1466                                    System.identityHashCode(mHandler));
1467                            if (params.traceMethod != null) {
1468                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1469                                        params.traceCookie);
1470                            }
1471                            return;
1472                        } else {
1473                            // Once we bind to the service, the first
1474                            // pending request will be processed.
1475                            mPendingInstalls.add(idx, params);
1476                        }
1477                    } else {
1478                        mPendingInstalls.add(idx, params);
1479                        // Already bound to the service. Just make
1480                        // sure we trigger off processing the first request.
1481                        if (idx == 0) {
1482                            mHandler.sendEmptyMessage(MCS_BOUND);
1483                        }
1484                    }
1485                    break;
1486                }
1487                case MCS_BOUND: {
1488                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1489                    if (msg.obj != null) {
1490                        mContainerService = (IMediaContainerService) msg.obj;
1491                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1492                                System.identityHashCode(mHandler));
1493                    }
1494                    if (mContainerService == null) {
1495                        if (!mBound) {
1496                            // Something seriously wrong since we are not bound and we are not
1497                            // waiting for connection. Bail out.
1498                            Slog.e(TAG, "Cannot bind to media container service");
1499                            for (HandlerParams params : mPendingInstalls) {
1500                                // Indicate service bind error
1501                                params.serviceError();
1502                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1503                                        System.identityHashCode(params));
1504                                if (params.traceMethod != null) {
1505                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1506                                            params.traceMethod, params.traceCookie);
1507                                }
1508                                return;
1509                            }
1510                            mPendingInstalls.clear();
1511                        } else {
1512                            Slog.w(TAG, "Waiting to connect to media container service");
1513                        }
1514                    } else if (mPendingInstalls.size() > 0) {
1515                        HandlerParams params = mPendingInstalls.get(0);
1516                        if (params != null) {
1517                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1518                                    System.identityHashCode(params));
1519                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1520                            if (params.startCopy()) {
1521                                // We are done...  look for more work or to
1522                                // go idle.
1523                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1524                                        "Checking for more work or unbind...");
1525                                // Delete pending install
1526                                if (mPendingInstalls.size() > 0) {
1527                                    mPendingInstalls.remove(0);
1528                                }
1529                                if (mPendingInstalls.size() == 0) {
1530                                    if (mBound) {
1531                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1532                                                "Posting delayed MCS_UNBIND");
1533                                        removeMessages(MCS_UNBIND);
1534                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1535                                        // Unbind after a little delay, to avoid
1536                                        // continual thrashing.
1537                                        sendMessageDelayed(ubmsg, 10000);
1538                                    }
1539                                } else {
1540                                    // There are more pending requests in queue.
1541                                    // Just post MCS_BOUND message to trigger processing
1542                                    // of next pending install.
1543                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1544                                            "Posting MCS_BOUND for next work");
1545                                    mHandler.sendEmptyMessage(MCS_BOUND);
1546                                }
1547                            }
1548                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1549                        }
1550                    } else {
1551                        // Should never happen ideally.
1552                        Slog.w(TAG, "Empty queue");
1553                    }
1554                    break;
1555                }
1556                case MCS_RECONNECT: {
1557                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1558                    if (mPendingInstalls.size() > 0) {
1559                        if (mBound) {
1560                            disconnectService();
1561                        }
1562                        if (!connectToService()) {
1563                            Slog.e(TAG, "Failed to bind to media container service");
1564                            for (HandlerParams params : mPendingInstalls) {
1565                                // Indicate service bind error
1566                                params.serviceError();
1567                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1568                                        System.identityHashCode(params));
1569                            }
1570                            mPendingInstalls.clear();
1571                        }
1572                    }
1573                    break;
1574                }
1575                case MCS_UNBIND: {
1576                    // If there is no actual work left, then time to unbind.
1577                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1578
1579                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1580                        if (mBound) {
1581                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1582
1583                            disconnectService();
1584                        }
1585                    } else if (mPendingInstalls.size() > 0) {
1586                        // There are more pending requests in queue.
1587                        // Just post MCS_BOUND message to trigger processing
1588                        // of next pending install.
1589                        mHandler.sendEmptyMessage(MCS_BOUND);
1590                    }
1591
1592                    break;
1593                }
1594                case MCS_GIVE_UP: {
1595                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1596                    HandlerParams params = mPendingInstalls.remove(0);
1597                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1598                            System.identityHashCode(params));
1599                    break;
1600                }
1601                case SEND_PENDING_BROADCAST: {
1602                    String packages[];
1603                    ArrayList<String> components[];
1604                    int size = 0;
1605                    int uids[];
1606                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1607                    synchronized (mPackages) {
1608                        if (mPendingBroadcasts == null) {
1609                            return;
1610                        }
1611                        size = mPendingBroadcasts.size();
1612                        if (size <= 0) {
1613                            // Nothing to be done. Just return
1614                            return;
1615                        }
1616                        packages = new String[size];
1617                        components = new ArrayList[size];
1618                        uids = new int[size];
1619                        int i = 0;  // filling out the above arrays
1620
1621                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1622                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1623                            Iterator<Map.Entry<String, ArrayList<String>>> it
1624                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1625                                            .entrySet().iterator();
1626                            while (it.hasNext() && i < size) {
1627                                Map.Entry<String, ArrayList<String>> ent = it.next();
1628                                packages[i] = ent.getKey();
1629                                components[i] = ent.getValue();
1630                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1631                                uids[i] = (ps != null)
1632                                        ? UserHandle.getUid(packageUserId, ps.appId)
1633                                        : -1;
1634                                i++;
1635                            }
1636                        }
1637                        size = i;
1638                        mPendingBroadcasts.clear();
1639                    }
1640                    // Send broadcasts
1641                    for (int i = 0; i < size; i++) {
1642                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1643                    }
1644                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1645                    break;
1646                }
1647                case START_CLEANING_PACKAGE: {
1648                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1649                    final String packageName = (String)msg.obj;
1650                    final int userId = msg.arg1;
1651                    final boolean andCode = msg.arg2 != 0;
1652                    synchronized (mPackages) {
1653                        if (userId == UserHandle.USER_ALL) {
1654                            int[] users = sUserManager.getUserIds();
1655                            for (int user : users) {
1656                                mSettings.addPackageToCleanLPw(
1657                                        new PackageCleanItem(user, packageName, andCode));
1658                            }
1659                        } else {
1660                            mSettings.addPackageToCleanLPw(
1661                                    new PackageCleanItem(userId, packageName, andCode));
1662                        }
1663                    }
1664                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1665                    startCleaningPackages();
1666                } break;
1667                case POST_INSTALL: {
1668                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1669
1670                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1671                    final boolean didRestore = (msg.arg2 != 0);
1672                    mRunningInstalls.delete(msg.arg1);
1673
1674                    if (data != null) {
1675                        InstallArgs args = data.args;
1676                        PackageInstalledInfo parentRes = data.res;
1677
1678                        final boolean grantPermissions = (args.installFlags
1679                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1680                        final boolean killApp = (args.installFlags
1681                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1682                        final boolean virtualPreload = ((args.installFlags
1683                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1684                        final String[] grantedPermissions = args.installGrantPermissions;
1685
1686                        // Handle the parent package
1687                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1688                                virtualPreload, grantedPermissions, didRestore,
1689                                args.installerPackageName, args.observer);
1690
1691                        // Handle the child packages
1692                        final int childCount = (parentRes.addedChildPackages != null)
1693                                ? parentRes.addedChildPackages.size() : 0;
1694                        for (int i = 0; i < childCount; i++) {
1695                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1696                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1697                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1698                                    args.installerPackageName, args.observer);
1699                        }
1700
1701                        // Log tracing if needed
1702                        if (args.traceMethod != null) {
1703                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1704                                    args.traceCookie);
1705                        }
1706                    } else {
1707                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1708                    }
1709
1710                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1711                } break;
1712                case UPDATED_MEDIA_STATUS: {
1713                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1714                    boolean reportStatus = msg.arg1 == 1;
1715                    boolean doGc = msg.arg2 == 1;
1716                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1717                    if (doGc) {
1718                        // Force a gc to clear up stale containers.
1719                        Runtime.getRuntime().gc();
1720                    }
1721                    if (msg.obj != null) {
1722                        @SuppressWarnings("unchecked")
1723                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1724                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1725                        // Unload containers
1726                        unloadAllContainers(args);
1727                    }
1728                    if (reportStatus) {
1729                        try {
1730                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1731                                    "Invoking StorageManagerService call back");
1732                            PackageHelper.getStorageManager().finishMediaUpdate();
1733                        } catch (RemoteException e) {
1734                            Log.e(TAG, "StorageManagerService not running?");
1735                        }
1736                    }
1737                } break;
1738                case WRITE_SETTINGS: {
1739                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1740                    synchronized (mPackages) {
1741                        removeMessages(WRITE_SETTINGS);
1742                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1743                        mSettings.writeLPr();
1744                        mDirtyUsers.clear();
1745                    }
1746                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1747                } break;
1748                case WRITE_PACKAGE_RESTRICTIONS: {
1749                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1750                    synchronized (mPackages) {
1751                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1752                        for (int userId : mDirtyUsers) {
1753                            mSettings.writePackageRestrictionsLPr(userId);
1754                        }
1755                        mDirtyUsers.clear();
1756                    }
1757                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1758                } break;
1759                case WRITE_PACKAGE_LIST: {
1760                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1761                    synchronized (mPackages) {
1762                        removeMessages(WRITE_PACKAGE_LIST);
1763                        mSettings.writePackageListLPr(msg.arg1);
1764                    }
1765                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1766                } break;
1767                case CHECK_PENDING_VERIFICATION: {
1768                    final int verificationId = msg.arg1;
1769                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1770
1771                    if ((state != null) && !state.timeoutExtended()) {
1772                        final InstallArgs args = state.getInstallArgs();
1773                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1774
1775                        Slog.i(TAG, "Verification timed out for " + originUri);
1776                        mPendingVerification.remove(verificationId);
1777
1778                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1779
1780                        final UserHandle user = args.getUser();
1781                        if (getDefaultVerificationResponse(user)
1782                                == PackageManager.VERIFICATION_ALLOW) {
1783                            Slog.i(TAG, "Continuing with installation of " + originUri);
1784                            state.setVerifierResponse(Binder.getCallingUid(),
1785                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1786                            broadcastPackageVerified(verificationId, originUri,
1787                                    PackageManager.VERIFICATION_ALLOW, user);
1788                            try {
1789                                ret = args.copyApk(mContainerService, true);
1790                            } catch (RemoteException e) {
1791                                Slog.e(TAG, "Could not contact the ContainerService");
1792                            }
1793                        } else {
1794                            broadcastPackageVerified(verificationId, originUri,
1795                                    PackageManager.VERIFICATION_REJECT, user);
1796                        }
1797
1798                        Trace.asyncTraceEnd(
1799                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1800
1801                        processPendingInstall(args, ret);
1802                        mHandler.sendEmptyMessage(MCS_UNBIND);
1803                    }
1804                    break;
1805                }
1806                case PACKAGE_VERIFIED: {
1807                    final int verificationId = msg.arg1;
1808
1809                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1810                    if (state == null) {
1811                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1812                        break;
1813                    }
1814
1815                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1816
1817                    state.setVerifierResponse(response.callerUid, response.code);
1818
1819                    if (state.isVerificationComplete()) {
1820                        mPendingVerification.remove(verificationId);
1821
1822                        final InstallArgs args = state.getInstallArgs();
1823                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1824
1825                        int ret;
1826                        if (state.isInstallAllowed()) {
1827                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1828                            broadcastPackageVerified(verificationId, originUri,
1829                                    response.code, state.getInstallArgs().getUser());
1830                            try {
1831                                ret = args.copyApk(mContainerService, true);
1832                            } catch (RemoteException e) {
1833                                Slog.e(TAG, "Could not contact the ContainerService");
1834                            }
1835                        } else {
1836                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1837                        }
1838
1839                        Trace.asyncTraceEnd(
1840                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1841
1842                        processPendingInstall(args, ret);
1843                        mHandler.sendEmptyMessage(MCS_UNBIND);
1844                    }
1845
1846                    break;
1847                }
1848                case START_INTENT_FILTER_VERIFICATIONS: {
1849                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1850                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1851                            params.replacing, params.pkg);
1852                    break;
1853                }
1854                case INTENT_FILTER_VERIFIED: {
1855                    final int verificationId = msg.arg1;
1856
1857                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1858                            verificationId);
1859                    if (state == null) {
1860                        Slog.w(TAG, "Invalid IntentFilter verification token "
1861                                + verificationId + " received");
1862                        break;
1863                    }
1864
1865                    final int userId = state.getUserId();
1866
1867                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1868                            "Processing IntentFilter verification with token:"
1869                            + verificationId + " and userId:" + userId);
1870
1871                    final IntentFilterVerificationResponse response =
1872                            (IntentFilterVerificationResponse) msg.obj;
1873
1874                    state.setVerifierResponse(response.callerUid, response.code);
1875
1876                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1877                            "IntentFilter verification with token:" + verificationId
1878                            + " and userId:" + userId
1879                            + " is settings verifier response with response code:"
1880                            + response.code);
1881
1882                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1883                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1884                                + response.getFailedDomainsString());
1885                    }
1886
1887                    if (state.isVerificationComplete()) {
1888                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1889                    } else {
1890                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1891                                "IntentFilter verification with token:" + verificationId
1892                                + " was not said to be complete");
1893                    }
1894
1895                    break;
1896                }
1897                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1898                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1899                            mInstantAppResolverConnection,
1900                            (InstantAppRequest) msg.obj,
1901                            mInstantAppInstallerActivity,
1902                            mHandler);
1903                }
1904            }
1905        }
1906    }
1907
1908    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1909            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1910            boolean launchedForRestore, String installerPackage,
1911            IPackageInstallObserver2 installObserver) {
1912        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1913            // Send the removed broadcasts
1914            if (res.removedInfo != null) {
1915                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1916            }
1917
1918            // Now that we successfully installed the package, grant runtime
1919            // permissions if requested before broadcasting the install. Also
1920            // for legacy apps in permission review mode we clear the permission
1921            // review flag which is used to emulate runtime permissions for
1922            // legacy apps.
1923            if (grantPermissions) {
1924                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1925            }
1926
1927            final boolean update = res.removedInfo != null
1928                    && res.removedInfo.removedPackage != null;
1929            final String installerPackageName =
1930                    res.installerPackageName != null
1931                            ? res.installerPackageName
1932                            : res.removedInfo != null
1933                                    ? res.removedInfo.installerPackageName
1934                                    : null;
1935
1936            // If this is the first time we have child packages for a disabled privileged
1937            // app that had no children, we grant requested runtime permissions to the new
1938            // children if the parent on the system image had them already granted.
1939            if (res.pkg.parentPackage != null) {
1940                synchronized (mPackages) {
1941                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1942                }
1943            }
1944
1945            synchronized (mPackages) {
1946                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1947            }
1948
1949            final String packageName = res.pkg.applicationInfo.packageName;
1950
1951            // Determine the set of users who are adding this package for
1952            // the first time vs. those who are seeing an update.
1953            int[] firstUsers = EMPTY_INT_ARRAY;
1954            int[] updateUsers = EMPTY_INT_ARRAY;
1955            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1956            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1957            for (int newUser : res.newUsers) {
1958                if (ps.getInstantApp(newUser)) {
1959                    continue;
1960                }
1961                if (allNewUsers) {
1962                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1963                    continue;
1964                }
1965                boolean isNew = true;
1966                for (int origUser : res.origUsers) {
1967                    if (origUser == newUser) {
1968                        isNew = false;
1969                        break;
1970                    }
1971                }
1972                if (isNew) {
1973                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1974                } else {
1975                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1976                }
1977            }
1978
1979            // Send installed broadcasts if the package is not a static shared lib.
1980            if (res.pkg.staticSharedLibName == null) {
1981                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1982
1983                // Send added for users that see the package for the first time
1984                // sendPackageAddedForNewUsers also deals with system apps
1985                int appId = UserHandle.getAppId(res.uid);
1986                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1987                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
1988                        virtualPreload /*startReceiver*/, appId, firstUsers);
1989
1990                // Send added for users that don't see the package for the first time
1991                Bundle extras = new Bundle(1);
1992                extras.putInt(Intent.EXTRA_UID, res.uid);
1993                if (update) {
1994                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1995                }
1996                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1997                        extras, 0 /*flags*/,
1998                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1999                if (installerPackageName != null) {
2000                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2001                            extras, 0 /*flags*/,
2002                            installerPackageName, null /*finishedReceiver*/, updateUsers);
2003                }
2004
2005                // Send replaced for users that don't see the package for the first time
2006                if (update) {
2007                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2008                            packageName, extras, 0 /*flags*/,
2009                            null /*targetPackage*/, null /*finishedReceiver*/,
2010                            updateUsers);
2011                    if (installerPackageName != null) {
2012                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2013                                extras, 0 /*flags*/,
2014                                installerPackageName, null /*finishedReceiver*/, updateUsers);
2015                    }
2016                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2017                            null /*package*/, null /*extras*/, 0 /*flags*/,
2018                            packageName /*targetPackage*/,
2019                            null /*finishedReceiver*/, updateUsers);
2020                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2021                    // First-install and we did a restore, so we're responsible for the
2022                    // first-launch broadcast.
2023                    if (DEBUG_BACKUP) {
2024                        Slog.i(TAG, "Post-restore of " + packageName
2025                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2026                    }
2027                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2028                }
2029
2030                // Send broadcast package appeared if forward locked/external for all users
2031                // treat asec-hosted packages like removable media on upgrade
2032                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2033                    if (DEBUG_INSTALL) {
2034                        Slog.i(TAG, "upgrading pkg " + res.pkg
2035                                + " is ASEC-hosted -> AVAILABLE");
2036                    }
2037                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2038                    ArrayList<String> pkgList = new ArrayList<>(1);
2039                    pkgList.add(packageName);
2040                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2041                }
2042            }
2043
2044            // Work that needs to happen on first install within each user
2045            if (firstUsers != null && firstUsers.length > 0) {
2046                synchronized (mPackages) {
2047                    for (int userId : firstUsers) {
2048                        // If this app is a browser and it's newly-installed for some
2049                        // users, clear any default-browser state in those users. The
2050                        // app's nature doesn't depend on the user, so we can just check
2051                        // its browser nature in any user and generalize.
2052                        if (packageIsBrowser(packageName, userId)) {
2053                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2054                        }
2055
2056                        // We may also need to apply pending (restored) runtime
2057                        // permission grants within these users.
2058                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2059                    }
2060                }
2061            }
2062
2063            // Log current value of "unknown sources" setting
2064            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2065                    getUnknownSourcesSettings());
2066
2067            // Remove the replaced package's older resources safely now
2068            // We delete after a gc for applications  on sdcard.
2069            if (res.removedInfo != null && res.removedInfo.args != null) {
2070                Runtime.getRuntime().gc();
2071                synchronized (mInstallLock) {
2072                    res.removedInfo.args.doPostDeleteLI(true);
2073                }
2074            } else {
2075                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2076                // and not block here.
2077                VMRuntime.getRuntime().requestConcurrentGC();
2078            }
2079
2080            // Notify DexManager that the package was installed for new users.
2081            // The updated users should already be indexed and the package code paths
2082            // should not change.
2083            // Don't notify the manager for ephemeral apps as they are not expected to
2084            // survive long enough to benefit of background optimizations.
2085            for (int userId : firstUsers) {
2086                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2087                // There's a race currently where some install events may interleave with an uninstall.
2088                // This can lead to package info being null (b/36642664).
2089                if (info != null) {
2090                    mDexManager.notifyPackageInstalled(info, userId);
2091                }
2092            }
2093        }
2094
2095        // If someone is watching installs - notify them
2096        if (installObserver != null) {
2097            try {
2098                Bundle extras = extrasForInstallResult(res);
2099                installObserver.onPackageInstalled(res.name, res.returnCode,
2100                        res.returnMsg, extras);
2101            } catch (RemoteException e) {
2102                Slog.i(TAG, "Observer no longer exists.");
2103            }
2104        }
2105    }
2106
2107    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2108            PackageParser.Package pkg) {
2109        if (pkg.parentPackage == null) {
2110            return;
2111        }
2112        if (pkg.requestedPermissions == null) {
2113            return;
2114        }
2115        final PackageSetting disabledSysParentPs = mSettings
2116                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2117        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2118                || !disabledSysParentPs.isPrivileged()
2119                || (disabledSysParentPs.childPackageNames != null
2120                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2121            return;
2122        }
2123        final int[] allUserIds = sUserManager.getUserIds();
2124        final int permCount = pkg.requestedPermissions.size();
2125        for (int i = 0; i < permCount; i++) {
2126            String permission = pkg.requestedPermissions.get(i);
2127            BasePermission bp = mSettings.mPermissions.get(permission);
2128            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2129                continue;
2130            }
2131            for (int userId : allUserIds) {
2132                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2133                        permission, userId)) {
2134                    grantRuntimePermission(pkg.packageName, permission, userId);
2135                }
2136            }
2137        }
2138    }
2139
2140    private StorageEventListener mStorageListener = new StorageEventListener() {
2141        @Override
2142        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2143            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2144                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2145                    final String volumeUuid = vol.getFsUuid();
2146
2147                    // Clean up any users or apps that were removed or recreated
2148                    // while this volume was missing
2149                    sUserManager.reconcileUsers(volumeUuid);
2150                    reconcileApps(volumeUuid);
2151
2152                    // Clean up any install sessions that expired or were
2153                    // cancelled while this volume was missing
2154                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2155
2156                    loadPrivatePackages(vol);
2157
2158                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2159                    unloadPrivatePackages(vol);
2160                }
2161            }
2162
2163            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2164                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2165                    updateExternalMediaStatus(true, false);
2166                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2167                    updateExternalMediaStatus(false, false);
2168                }
2169            }
2170        }
2171
2172        @Override
2173        public void onVolumeForgotten(String fsUuid) {
2174            if (TextUtils.isEmpty(fsUuid)) {
2175                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2176                return;
2177            }
2178
2179            // Remove any apps installed on the forgotten volume
2180            synchronized (mPackages) {
2181                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2182                for (PackageSetting ps : packages) {
2183                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2184                    deletePackageVersioned(new VersionedPackage(ps.name,
2185                            PackageManager.VERSION_CODE_HIGHEST),
2186                            new LegacyPackageDeleteObserver(null).getBinder(),
2187                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2188                    // Try very hard to release any references to this package
2189                    // so we don't risk the system server being killed due to
2190                    // open FDs
2191                    AttributeCache.instance().removePackage(ps.name);
2192                }
2193
2194                mSettings.onVolumeForgotten(fsUuid);
2195                mSettings.writeLPr();
2196            }
2197        }
2198    };
2199
2200    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2201            String[] grantedPermissions) {
2202        for (int userId : userIds) {
2203            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2204        }
2205    }
2206
2207    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2208            String[] grantedPermissions) {
2209        PackageSetting ps = (PackageSetting) pkg.mExtras;
2210        if (ps == null) {
2211            return;
2212        }
2213
2214        PermissionsState permissionsState = ps.getPermissionsState();
2215
2216        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2217                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2218
2219        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2220                >= Build.VERSION_CODES.M;
2221
2222        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2223
2224        for (String permission : pkg.requestedPermissions) {
2225            final BasePermission bp;
2226            synchronized (mPackages) {
2227                bp = mSettings.mPermissions.get(permission);
2228            }
2229            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2230                    && (!instantApp || bp.isInstant())
2231                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2232                    && (grantedPermissions == null
2233                           || ArrayUtils.contains(grantedPermissions, permission))) {
2234                final int flags = permissionsState.getPermissionFlags(permission, userId);
2235                if (supportsRuntimePermissions) {
2236                    // Installer cannot change immutable permissions.
2237                    if ((flags & immutableFlags) == 0) {
2238                        grantRuntimePermission(pkg.packageName, permission, userId);
2239                    }
2240                } else if (mPermissionReviewRequired) {
2241                    // In permission review mode we clear the review flag when we
2242                    // are asked to install the app with all permissions granted.
2243                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2244                        updatePermissionFlags(permission, pkg.packageName,
2245                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2246                    }
2247                }
2248            }
2249        }
2250    }
2251
2252    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2253        Bundle extras = null;
2254        switch (res.returnCode) {
2255            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2256                extras = new Bundle();
2257                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2258                        res.origPermission);
2259                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2260                        res.origPackage);
2261                break;
2262            }
2263            case PackageManager.INSTALL_SUCCEEDED: {
2264                extras = new Bundle();
2265                extras.putBoolean(Intent.EXTRA_REPLACING,
2266                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2267                break;
2268            }
2269        }
2270        return extras;
2271    }
2272
2273    void scheduleWriteSettingsLocked() {
2274        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2275            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2276        }
2277    }
2278
2279    void scheduleWritePackageListLocked(int userId) {
2280        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2281            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2282            msg.arg1 = userId;
2283            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2284        }
2285    }
2286
2287    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2288        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2289        scheduleWritePackageRestrictionsLocked(userId);
2290    }
2291
2292    void scheduleWritePackageRestrictionsLocked(int userId) {
2293        final int[] userIds = (userId == UserHandle.USER_ALL)
2294                ? sUserManager.getUserIds() : new int[]{userId};
2295        for (int nextUserId : userIds) {
2296            if (!sUserManager.exists(nextUserId)) return;
2297            mDirtyUsers.add(nextUserId);
2298            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2299                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2300            }
2301        }
2302    }
2303
2304    public static PackageManagerService main(Context context, Installer installer,
2305            boolean factoryTest, boolean onlyCore) {
2306        // Self-check for initial settings.
2307        PackageManagerServiceCompilerMapping.checkProperties();
2308
2309        PackageManagerService m = new PackageManagerService(context, installer,
2310                factoryTest, onlyCore);
2311        m.enableSystemUserPackages();
2312        ServiceManager.addService("package", m);
2313        final PackageManagerNative pmn = m.new PackageManagerNative();
2314        ServiceManager.addService("package_native", pmn);
2315        return m;
2316    }
2317
2318    private void enableSystemUserPackages() {
2319        if (!UserManager.isSplitSystemUser()) {
2320            return;
2321        }
2322        // For system user, enable apps based on the following conditions:
2323        // - app is whitelisted or belong to one of these groups:
2324        //   -- system app which has no launcher icons
2325        //   -- system app which has INTERACT_ACROSS_USERS permission
2326        //   -- system IME app
2327        // - app is not in the blacklist
2328        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2329        Set<String> enableApps = new ArraySet<>();
2330        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2331                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2332                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2333        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2334        enableApps.addAll(wlApps);
2335        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2336                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2337        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2338        enableApps.removeAll(blApps);
2339        Log.i(TAG, "Applications installed for system user: " + enableApps);
2340        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2341                UserHandle.SYSTEM);
2342        final int allAppsSize = allAps.size();
2343        synchronized (mPackages) {
2344            for (int i = 0; i < allAppsSize; i++) {
2345                String pName = allAps.get(i);
2346                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2347                // Should not happen, but we shouldn't be failing if it does
2348                if (pkgSetting == null) {
2349                    continue;
2350                }
2351                boolean install = enableApps.contains(pName);
2352                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2353                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2354                            + " for system user");
2355                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2356                }
2357            }
2358            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2359        }
2360    }
2361
2362    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2363        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2364                Context.DISPLAY_SERVICE);
2365        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2366    }
2367
2368    /**
2369     * Requests that files preopted on a secondary system partition be copied to the data partition
2370     * if possible.  Note that the actual copying of the files is accomplished by init for security
2371     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2372     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2373     */
2374    private static void requestCopyPreoptedFiles() {
2375        final int WAIT_TIME_MS = 100;
2376        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2377        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2378            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2379            // We will wait for up to 100 seconds.
2380            final long timeStart = SystemClock.uptimeMillis();
2381            final long timeEnd = timeStart + 100 * 1000;
2382            long timeNow = timeStart;
2383            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2384                try {
2385                    Thread.sleep(WAIT_TIME_MS);
2386                } catch (InterruptedException e) {
2387                    // Do nothing
2388                }
2389                timeNow = SystemClock.uptimeMillis();
2390                if (timeNow > timeEnd) {
2391                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2392                    Slog.wtf(TAG, "cppreopt did not finish!");
2393                    break;
2394                }
2395            }
2396
2397            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2398        }
2399    }
2400
2401    public PackageManagerService(Context context, Installer installer,
2402            boolean factoryTest, boolean onlyCore) {
2403        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2404        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2405        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2406                SystemClock.uptimeMillis());
2407
2408        if (mSdkVersion <= 0) {
2409            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2410        }
2411
2412        mContext = context;
2413
2414        mPermissionReviewRequired = context.getResources().getBoolean(
2415                R.bool.config_permissionReviewRequired);
2416
2417        mFactoryTest = factoryTest;
2418        mOnlyCore = onlyCore;
2419        mMetrics = new DisplayMetrics();
2420        mSettings = new Settings(mPackages);
2421        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2422                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2423        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2424                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2425        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2426                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2427        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2428                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2429        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2430                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2431        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2432                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2433
2434        String separateProcesses = SystemProperties.get("debug.separate_processes");
2435        if (separateProcesses != null && separateProcesses.length() > 0) {
2436            if ("*".equals(separateProcesses)) {
2437                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2438                mSeparateProcesses = null;
2439                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2440            } else {
2441                mDefParseFlags = 0;
2442                mSeparateProcesses = separateProcesses.split(",");
2443                Slog.w(TAG, "Running with debug.separate_processes: "
2444                        + separateProcesses);
2445            }
2446        } else {
2447            mDefParseFlags = 0;
2448            mSeparateProcesses = null;
2449        }
2450
2451        mInstaller = installer;
2452        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2453                "*dexopt*");
2454        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2455        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2456
2457        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2458                FgThread.get().getLooper());
2459
2460        getDefaultDisplayMetrics(context, mMetrics);
2461
2462        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2463        SystemConfig systemConfig = SystemConfig.getInstance();
2464        mGlobalGids = systemConfig.getGlobalGids();
2465        mSystemPermissions = systemConfig.getSystemPermissions();
2466        mAvailableFeatures = systemConfig.getAvailableFeatures();
2467        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2468
2469        mProtectedPackages = new ProtectedPackages(mContext);
2470
2471        synchronized (mInstallLock) {
2472        // writer
2473        synchronized (mPackages) {
2474            mHandlerThread = new ServiceThread(TAG,
2475                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2476            mHandlerThread.start();
2477            mHandler = new PackageHandler(mHandlerThread.getLooper());
2478            mProcessLoggingHandler = new ProcessLoggingHandler();
2479            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2480
2481            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2482            mInstantAppRegistry = new InstantAppRegistry(this);
2483
2484            File dataDir = Environment.getDataDirectory();
2485            mAppInstallDir = new File(dataDir, "app");
2486            mAppLib32InstallDir = new File(dataDir, "app-lib");
2487            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2488            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2489            sUserManager = new UserManagerService(context, this,
2490                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2491
2492            // Propagate permission configuration in to package manager.
2493            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2494                    = systemConfig.getPermissions();
2495            for (int i=0; i<permConfig.size(); i++) {
2496                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2497                BasePermission bp = mSettings.mPermissions.get(perm.name);
2498                if (bp == null) {
2499                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2500                    mSettings.mPermissions.put(perm.name, bp);
2501                }
2502                if (perm.gids != null) {
2503                    bp.setGids(perm.gids, perm.perUser);
2504                }
2505            }
2506
2507            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2508            final int builtInLibCount = libConfig.size();
2509            for (int i = 0; i < builtInLibCount; i++) {
2510                String name = libConfig.keyAt(i);
2511                String path = libConfig.valueAt(i);
2512                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2513                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2514            }
2515
2516            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2517
2518            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2519            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2520            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2521
2522            // Clean up orphaned packages for which the code path doesn't exist
2523            // and they are an update to a system app - caused by bug/32321269
2524            final int packageSettingCount = mSettings.mPackages.size();
2525            for (int i = packageSettingCount - 1; i >= 0; i--) {
2526                PackageSetting ps = mSettings.mPackages.valueAt(i);
2527                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2528                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2529                    mSettings.mPackages.removeAt(i);
2530                    mSettings.enableSystemPackageLPw(ps.name);
2531                }
2532            }
2533
2534            if (mFirstBoot) {
2535                requestCopyPreoptedFiles();
2536            }
2537
2538            String customResolverActivity = Resources.getSystem().getString(
2539                    R.string.config_customResolverActivity);
2540            if (TextUtils.isEmpty(customResolverActivity)) {
2541                customResolverActivity = null;
2542            } else {
2543                mCustomResolverComponentName = ComponentName.unflattenFromString(
2544                        customResolverActivity);
2545            }
2546
2547            long startTime = SystemClock.uptimeMillis();
2548
2549            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2550                    startTime);
2551
2552            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2553            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2554
2555            if (bootClassPath == null) {
2556                Slog.w(TAG, "No BOOTCLASSPATH found!");
2557            }
2558
2559            if (systemServerClassPath == null) {
2560                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2561            }
2562
2563            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2564
2565            final VersionInfo ver = mSettings.getInternalVersion();
2566            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2567            if (mIsUpgrade) {
2568                logCriticalInfo(Log.INFO,
2569                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2570            }
2571
2572            // when upgrading from pre-M, promote system app permissions from install to runtime
2573            mPromoteSystemApps =
2574                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2575
2576            // When upgrading from pre-N, we need to handle package extraction like first boot,
2577            // as there is no profiling data available.
2578            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2579
2580            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2581
2582            // save off the names of pre-existing system packages prior to scanning; we don't
2583            // want to automatically grant runtime permissions for new system apps
2584            if (mPromoteSystemApps) {
2585                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2586                while (pkgSettingIter.hasNext()) {
2587                    PackageSetting ps = pkgSettingIter.next();
2588                    if (isSystemApp(ps)) {
2589                        mExistingSystemPackages.add(ps.name);
2590                    }
2591                }
2592            }
2593
2594            mCacheDir = preparePackageParserCache(mIsUpgrade);
2595
2596            // Set flag to monitor and not change apk file paths when
2597            // scanning install directories.
2598            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2599
2600            if (mIsUpgrade || mFirstBoot) {
2601                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2602            }
2603
2604            // Collect vendor overlay packages. (Do this before scanning any apps.)
2605            // For security and version matching reason, only consider
2606            // overlay packages if they reside in the right directory.
2607            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2608                    | PackageParser.PARSE_IS_SYSTEM
2609                    | PackageParser.PARSE_IS_SYSTEM_DIR
2610                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2611
2612            mParallelPackageParserCallback.findStaticOverlayPackages();
2613
2614            // Find base frameworks (resource packages without code).
2615            scanDirTracedLI(frameworkDir, mDefParseFlags
2616                    | PackageParser.PARSE_IS_SYSTEM
2617                    | PackageParser.PARSE_IS_SYSTEM_DIR
2618                    | PackageParser.PARSE_IS_PRIVILEGED,
2619                    scanFlags | SCAN_NO_DEX, 0);
2620
2621            // Collected privileged system packages.
2622            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2623            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2624                    | PackageParser.PARSE_IS_SYSTEM
2625                    | PackageParser.PARSE_IS_SYSTEM_DIR
2626                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2627
2628            // Collect ordinary system packages.
2629            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2630            scanDirTracedLI(systemAppDir, mDefParseFlags
2631                    | PackageParser.PARSE_IS_SYSTEM
2632                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2633
2634            // Collect all vendor packages.
2635            File vendorAppDir = new File("/vendor/app");
2636            try {
2637                vendorAppDir = vendorAppDir.getCanonicalFile();
2638            } catch (IOException e) {
2639                // failed to look up canonical path, continue with original one
2640            }
2641            scanDirTracedLI(vendorAppDir, mDefParseFlags
2642                    | PackageParser.PARSE_IS_SYSTEM
2643                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2644
2645            // Collect all OEM packages.
2646            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2647            scanDirTracedLI(oemAppDir, mDefParseFlags
2648                    | PackageParser.PARSE_IS_SYSTEM
2649                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2650
2651            // Prune any system packages that no longer exist.
2652            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2653            // Stub packages must either be replaced with full versions in the /data
2654            // partition or be disabled.
2655            final List<String> stubSystemApps = new ArrayList<>();
2656            if (!mOnlyCore) {
2657                // do this first before mucking with mPackages for the "expecting better" case
2658                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2659                while (pkgIterator.hasNext()) {
2660                    final PackageParser.Package pkg = pkgIterator.next();
2661                    if (pkg.isStub) {
2662                        stubSystemApps.add(pkg.packageName);
2663                    }
2664                }
2665
2666                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2667                while (psit.hasNext()) {
2668                    PackageSetting ps = psit.next();
2669
2670                    /*
2671                     * If this is not a system app, it can't be a
2672                     * disable system app.
2673                     */
2674                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2675                        continue;
2676                    }
2677
2678                    /*
2679                     * If the package is scanned, it's not erased.
2680                     */
2681                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2682                    if (scannedPkg != null) {
2683                        /*
2684                         * If the system app is both scanned and in the
2685                         * disabled packages list, then it must have been
2686                         * added via OTA. Remove it from the currently
2687                         * scanned package so the previously user-installed
2688                         * application can be scanned.
2689                         */
2690                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2691                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2692                                    + ps.name + "; removing system app.  Last known codePath="
2693                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2694                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2695                                    + scannedPkg.mVersionCode);
2696                            removePackageLI(scannedPkg, true);
2697                            mExpectingBetter.put(ps.name, ps.codePath);
2698                        }
2699
2700                        continue;
2701                    }
2702
2703                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2704                        psit.remove();
2705                        logCriticalInfo(Log.WARN, "System package " + ps.name
2706                                + " no longer exists; it's data will be wiped");
2707                        // Actual deletion of code and data will be handled by later
2708                        // reconciliation step
2709                    } else {
2710                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2711                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2712                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2713                        }
2714                    }
2715                }
2716            }
2717
2718            //look for any incomplete package installations
2719            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2720            for (int i = 0; i < deletePkgsList.size(); i++) {
2721                // Actual deletion of code and data will be handled by later
2722                // reconciliation step
2723                final String packageName = deletePkgsList.get(i).name;
2724                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2725                synchronized (mPackages) {
2726                    mSettings.removePackageLPw(packageName);
2727                }
2728            }
2729
2730            //delete tmp files
2731            deleteTempPackageFiles();
2732
2733            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2734
2735            // Remove any shared userIDs that have no associated packages
2736            mSettings.pruneSharedUsersLPw();
2737            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2738            final int systemPackagesCount = mPackages.size();
2739            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2740                    + " ms, packageCount: " + systemPackagesCount
2741                    + " , timePerPackage: "
2742                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2743                    + " , cached: " + cachedSystemApps);
2744            if (mIsUpgrade && systemPackagesCount > 0) {
2745                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2746                        ((int) systemScanTime) / systemPackagesCount);
2747            }
2748            if (!mOnlyCore) {
2749                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2750                        SystemClock.uptimeMillis());
2751                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2752
2753                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2754                        | PackageParser.PARSE_FORWARD_LOCK,
2755                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2756
2757                // Remove disable package settings for updated system apps that were
2758                // removed via an OTA. If the update is no longer present, remove the
2759                // app completely. Otherwise, revoke their system privileges.
2760                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2761                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2762                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2763
2764                    final String msg;
2765                    if (deletedPkg == null) {
2766                        // should have found an update, but, we didn't; remove everything
2767                        msg = "Updated system package " + deletedAppName
2768                                + " no longer exists; removing its data";
2769                        // Actual deletion of code and data will be handled by later
2770                        // reconciliation step
2771                    } else {
2772                        // found an update; revoke system privileges
2773                        msg = "Updated system package + " + deletedAppName
2774                                + " no longer exists; revoking system privileges";
2775
2776                        // Don't do anything if a stub is removed from the system image. If
2777                        // we were to remove the uncompressed version from the /data partition,
2778                        // this is where it'd be done.
2779
2780                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2781                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2782                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2783                    }
2784                    logCriticalInfo(Log.WARN, msg);
2785                }
2786
2787                /*
2788                 * Make sure all system apps that we expected to appear on
2789                 * the userdata partition actually showed up. If they never
2790                 * appeared, crawl back and revive the system version.
2791                 */
2792                for (int i = 0; i < mExpectingBetter.size(); i++) {
2793                    final String packageName = mExpectingBetter.keyAt(i);
2794                    if (!mPackages.containsKey(packageName)) {
2795                        final File scanFile = mExpectingBetter.valueAt(i);
2796
2797                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2798                                + " but never showed up; reverting to system");
2799
2800                        int reparseFlags = mDefParseFlags;
2801                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2802                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2803                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2804                                    | PackageParser.PARSE_IS_PRIVILEGED;
2805                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2806                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2807                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2808                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2809                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2810                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2811                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2812                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2813                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2814                        } else {
2815                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2816                            continue;
2817                        }
2818
2819                        mSettings.enableSystemPackageLPw(packageName);
2820
2821                        try {
2822                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2823                        } catch (PackageManagerException e) {
2824                            Slog.e(TAG, "Failed to parse original system package: "
2825                                    + e.getMessage());
2826                        }
2827                    }
2828                }
2829
2830                // Uncompress and install any stubbed system applications.
2831                // This must be done last to ensure all stubs are replaced or disabled.
2832                decompressSystemApplications(stubSystemApps, scanFlags);
2833
2834                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2835                                - cachedSystemApps;
2836
2837                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2838                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2839                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2840                        + " ms, packageCount: " + dataPackagesCount
2841                        + " , timePerPackage: "
2842                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2843                        + " , cached: " + cachedNonSystemApps);
2844                if (mIsUpgrade && dataPackagesCount > 0) {
2845                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2846                            ((int) dataScanTime) / dataPackagesCount);
2847                }
2848            }
2849            mExpectingBetter.clear();
2850
2851            // Resolve the storage manager.
2852            mStorageManagerPackage = getStorageManagerPackageName();
2853
2854            // Resolve protected action filters. Only the setup wizard is allowed to
2855            // have a high priority filter for these actions.
2856            mSetupWizardPackage = getSetupWizardPackageName();
2857            if (mProtectedFilters.size() > 0) {
2858                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2859                    Slog.i(TAG, "No setup wizard;"
2860                        + " All protected intents capped to priority 0");
2861                }
2862                for (ActivityIntentInfo filter : mProtectedFilters) {
2863                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2864                        if (DEBUG_FILTERS) {
2865                            Slog.i(TAG, "Found setup wizard;"
2866                                + " allow priority " + filter.getPriority() + ";"
2867                                + " package: " + filter.activity.info.packageName
2868                                + " activity: " + filter.activity.className
2869                                + " priority: " + filter.getPriority());
2870                        }
2871                        // skip setup wizard; allow it to keep the high priority filter
2872                        continue;
2873                    }
2874                    if (DEBUG_FILTERS) {
2875                        Slog.i(TAG, "Protected action; cap priority to 0;"
2876                                + " package: " + filter.activity.info.packageName
2877                                + " activity: " + filter.activity.className
2878                                + " origPrio: " + filter.getPriority());
2879                    }
2880                    filter.setPriority(0);
2881                }
2882            }
2883            mDeferProtectedFilters = false;
2884            mProtectedFilters.clear();
2885
2886            // Now that we know all of the shared libraries, update all clients to have
2887            // the correct library paths.
2888            updateAllSharedLibrariesLPw(null);
2889
2890            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2891                // NOTE: We ignore potential failures here during a system scan (like
2892                // the rest of the commands above) because there's precious little we
2893                // can do about it. A settings error is reported, though.
2894                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2895            }
2896
2897            // Now that we know all the packages we are keeping,
2898            // read and update their last usage times.
2899            mPackageUsage.read(mPackages);
2900            mCompilerStats.read();
2901
2902            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2903                    SystemClock.uptimeMillis());
2904            Slog.i(TAG, "Time to scan packages: "
2905                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2906                    + " seconds");
2907
2908            // If the platform SDK has changed since the last time we booted,
2909            // we need to re-grant app permission to catch any new ones that
2910            // appear.  This is really a hack, and means that apps can in some
2911            // cases get permissions that the user didn't initially explicitly
2912            // allow...  it would be nice to have some better way to handle
2913            // this situation.
2914            int updateFlags = UPDATE_PERMISSIONS_ALL;
2915            if (ver.sdkVersion != mSdkVersion) {
2916                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2917                        + mSdkVersion + "; regranting permissions for internal storage");
2918                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2919            }
2920            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2921            ver.sdkVersion = mSdkVersion;
2922
2923            // If this is the first boot or an update from pre-M, and it is a normal
2924            // boot, then we need to initialize the default preferred apps across
2925            // all defined users.
2926            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2927                for (UserInfo user : sUserManager.getUsers(true)) {
2928                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2929                    applyFactoryDefaultBrowserLPw(user.id);
2930                    primeDomainVerificationsLPw(user.id);
2931                }
2932            }
2933
2934            // Prepare storage for system user really early during boot,
2935            // since core system apps like SettingsProvider and SystemUI
2936            // can't wait for user to start
2937            final int storageFlags;
2938            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2939                storageFlags = StorageManager.FLAG_STORAGE_DE;
2940            } else {
2941                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2942            }
2943            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2944                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2945                    true /* onlyCoreApps */);
2946            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2947                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2948                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2949                traceLog.traceBegin("AppDataFixup");
2950                try {
2951                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2952                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2953                } catch (InstallerException e) {
2954                    Slog.w(TAG, "Trouble fixing GIDs", e);
2955                }
2956                traceLog.traceEnd();
2957
2958                traceLog.traceBegin("AppDataPrepare");
2959                if (deferPackages == null || deferPackages.isEmpty()) {
2960                    return;
2961                }
2962                int count = 0;
2963                for (String pkgName : deferPackages) {
2964                    PackageParser.Package pkg = null;
2965                    synchronized (mPackages) {
2966                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2967                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2968                            pkg = ps.pkg;
2969                        }
2970                    }
2971                    if (pkg != null) {
2972                        synchronized (mInstallLock) {
2973                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2974                                    true /* maybeMigrateAppData */);
2975                        }
2976                        count++;
2977                    }
2978                }
2979                traceLog.traceEnd();
2980                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2981            }, "prepareAppData");
2982
2983            // If this is first boot after an OTA, and a normal boot, then
2984            // we need to clear code cache directories.
2985            // Note that we do *not* clear the application profiles. These remain valid
2986            // across OTAs and are used to drive profile verification (post OTA) and
2987            // profile compilation (without waiting to collect a fresh set of profiles).
2988            if (mIsUpgrade && !onlyCore) {
2989                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2990                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2991                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2992                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2993                        // No apps are running this early, so no need to freeze
2994                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2995                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2996                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2997                    }
2998                }
2999                ver.fingerprint = Build.FINGERPRINT;
3000            }
3001
3002            checkDefaultBrowser();
3003
3004            // clear only after permissions and other defaults have been updated
3005            mExistingSystemPackages.clear();
3006            mPromoteSystemApps = false;
3007
3008            // All the changes are done during package scanning.
3009            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3010
3011            // can downgrade to reader
3012            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3013            mSettings.writeLPr();
3014            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3015            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3016                    SystemClock.uptimeMillis());
3017
3018            if (!mOnlyCore) {
3019                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3020                mRequiredInstallerPackage = getRequiredInstallerLPr();
3021                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3022                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3023                if (mIntentFilterVerifierComponent != null) {
3024                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3025                            mIntentFilterVerifierComponent);
3026                } else {
3027                    mIntentFilterVerifier = null;
3028                }
3029                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3030                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3031                        SharedLibraryInfo.VERSION_UNDEFINED);
3032                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3033                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3034                        SharedLibraryInfo.VERSION_UNDEFINED);
3035            } else {
3036                mRequiredVerifierPackage = null;
3037                mRequiredInstallerPackage = null;
3038                mRequiredUninstallerPackage = null;
3039                mIntentFilterVerifierComponent = null;
3040                mIntentFilterVerifier = null;
3041                mServicesSystemSharedLibraryPackageName = null;
3042                mSharedSystemSharedLibraryPackageName = null;
3043            }
3044
3045            mInstallerService = new PackageInstallerService(context, this);
3046            final Pair<ComponentName, String> instantAppResolverComponent =
3047                    getInstantAppResolverLPr();
3048            if (instantAppResolverComponent != null) {
3049                if (DEBUG_EPHEMERAL) {
3050                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3051                }
3052                mInstantAppResolverConnection = new EphemeralResolverConnection(
3053                        mContext, instantAppResolverComponent.first,
3054                        instantAppResolverComponent.second);
3055                mInstantAppResolverSettingsComponent =
3056                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3057            } else {
3058                mInstantAppResolverConnection = null;
3059                mInstantAppResolverSettingsComponent = null;
3060            }
3061            updateInstantAppInstallerLocked(null);
3062
3063            // Read and update the usage of dex files.
3064            // Do this at the end of PM init so that all the packages have their
3065            // data directory reconciled.
3066            // At this point we know the code paths of the packages, so we can validate
3067            // the disk file and build the internal cache.
3068            // The usage file is expected to be small so loading and verifying it
3069            // should take a fairly small time compare to the other activities (e.g. package
3070            // scanning).
3071            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3072            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3073            for (int userId : currentUserIds) {
3074                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3075            }
3076            mDexManager.load(userPackages);
3077            if (mIsUpgrade) {
3078                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3079                        (int) (SystemClock.uptimeMillis() - startTime));
3080            }
3081        } // synchronized (mPackages)
3082        } // synchronized (mInstallLock)
3083
3084        // Now after opening every single application zip, make sure they
3085        // are all flushed.  Not really needed, but keeps things nice and
3086        // tidy.
3087        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3088        Runtime.getRuntime().gc();
3089        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3090
3091        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3092        FallbackCategoryProvider.loadFallbacks();
3093        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3094
3095        // The initial scanning above does many calls into installd while
3096        // holding the mPackages lock, but we're mostly interested in yelling
3097        // once we have a booted system.
3098        mInstaller.setWarnIfHeld(mPackages);
3099
3100        // Expose private service for system components to use.
3101        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3102        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3103    }
3104
3105    /**
3106     * Uncompress and install stub applications.
3107     * <p>In order to save space on the system partition, some applications are shipped in a
3108     * compressed form. In addition the compressed bits for the full application, the
3109     * system image contains a tiny stub comprised of only the Android manifest.
3110     * <p>During the first boot, attempt to uncompress and install the full application. If
3111     * the application can't be installed for any reason, disable the stub and prevent
3112     * uncompressing the full application during future boots.
3113     * <p>In order to forcefully attempt an installation of a full application, go to app
3114     * settings and enable the application.
3115     */
3116    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3117        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3118            final String pkgName = stubSystemApps.get(i);
3119            // skip if the system package is already disabled
3120            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3121                stubSystemApps.remove(i);
3122                continue;
3123            }
3124            // skip if the package isn't installed (?!); this should never happen
3125            final PackageParser.Package pkg = mPackages.get(pkgName);
3126            if (pkg == null) {
3127                stubSystemApps.remove(i);
3128                continue;
3129            }
3130            // skip if the package has been disabled by the user
3131            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3132            if (ps != null) {
3133                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3134                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3135                    stubSystemApps.remove(i);
3136                    continue;
3137                }
3138            }
3139
3140            if (DEBUG_COMPRESSION) {
3141                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3142            }
3143
3144            // uncompress the binary to its eventual destination on /data
3145            final File scanFile = decompressPackage(pkg);
3146            if (scanFile == null) {
3147                continue;
3148            }
3149
3150            // install the package to replace the stub on /system
3151            try {
3152                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3153                removePackageLI(pkg, true /*chatty*/);
3154                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3155                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3156                        UserHandle.USER_SYSTEM, "android");
3157                stubSystemApps.remove(i);
3158                continue;
3159            } catch (PackageManagerException e) {
3160                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3161            }
3162
3163            // any failed attempt to install the package will be cleaned up later
3164        }
3165
3166        // disable any stub still left; these failed to install the full application
3167        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3168            final String pkgName = stubSystemApps.get(i);
3169            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3170            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3171                    UserHandle.USER_SYSTEM, "android");
3172            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3173        }
3174    }
3175
3176    private int decompressFile(File srcFile, File dstFile) throws ErrnoException {
3177        if (DEBUG_COMPRESSION) {
3178            Slog.i(TAG, "Decompress file"
3179                    + "; src: " + srcFile.getAbsolutePath()
3180                    + ", dst: " + dstFile.getAbsolutePath());
3181        }
3182        try (
3183                InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile));
3184                OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/);
3185        ) {
3186            Streams.copy(fileIn, fileOut);
3187            Os.chmod(dstFile.getAbsolutePath(), 0644);
3188            return PackageManager.INSTALL_SUCCEEDED;
3189        } catch (IOException e) {
3190            logCriticalInfo(Log.ERROR, "Failed to decompress file"
3191                    + "; src: " + srcFile.getAbsolutePath()
3192                    + ", dst: " + dstFile.getAbsolutePath());
3193        }
3194        return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3195    }
3196
3197    private File[] getCompressedFiles(String codePath) {
3198        return new File(codePath).listFiles(new FilenameFilter() {
3199            @Override
3200            public boolean accept(File dir, String name) {
3201                return name.toLowerCase().endsWith(COMPRESSED_EXTENSION);
3202            }
3203        });
3204    }
3205
3206    private boolean compressedFileExists(String codePath) {
3207        final File[] compressedFiles = getCompressedFiles(codePath);
3208        return compressedFiles != null && compressedFiles.length > 0;
3209    }
3210
3211    /**
3212     * Decompresses the given package on the system image onto
3213     * the /data partition.
3214     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3215     */
3216    private File decompressPackage(PackageParser.Package pkg) {
3217        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3218        if (compressedFiles == null || compressedFiles.length == 0) {
3219            if (DEBUG_COMPRESSION) {
3220                Slog.i(TAG, "No files to decompress");
3221            }
3222            return null;
3223        }
3224        final File dstCodePath =
3225                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3226        int ret = PackageManager.INSTALL_SUCCEEDED;
3227        try {
3228            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3229            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3230            for (File srcFile : compressedFiles) {
3231                final String srcFileName = srcFile.getName();
3232                final String dstFileName = srcFileName.substring(
3233                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3234                final File dstFile = new File(dstCodePath, dstFileName);
3235                ret = decompressFile(srcFile, dstFile);
3236                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3237                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3238                            + "; pkg: " + pkg.packageName
3239                            + ", file: " + dstFileName);
3240                    break;
3241                }
3242            }
3243        } catch (ErrnoException e) {
3244            logCriticalInfo(Log.ERROR, "Failed to decompress"
3245                    + "; pkg: " + pkg.packageName
3246                    + ", err: " + e.errno);
3247        }
3248        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3249            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3250            NativeLibraryHelper.Handle handle = null;
3251            try {
3252                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3253                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3254                        null /*abiOverride*/);
3255            } catch (IOException e) {
3256                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3257                        + "; pkg: " + pkg.packageName);
3258                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3259            } finally {
3260                IoUtils.closeQuietly(handle);
3261            }
3262        }
3263        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3264            if (dstCodePath == null || !dstCodePath.exists()) {
3265                return null;
3266            }
3267            removeCodePathLI(dstCodePath);
3268            return null;
3269        }
3270        return dstCodePath;
3271    }
3272
3273    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3274        // we're only interested in updating the installer appliction when 1) it's not
3275        // already set or 2) the modified package is the installer
3276        if (mInstantAppInstallerActivity != null
3277                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3278                        .equals(modifiedPackage)) {
3279            return;
3280        }
3281        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3282    }
3283
3284    private static File preparePackageParserCache(boolean isUpgrade) {
3285        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3286            return null;
3287        }
3288
3289        // Disable package parsing on eng builds to allow for faster incremental development.
3290        if (Build.IS_ENG) {
3291            return null;
3292        }
3293
3294        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3295            Slog.i(TAG, "Disabling package parser cache due to system property.");
3296            return null;
3297        }
3298
3299        // The base directory for the package parser cache lives under /data/system/.
3300        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3301                "package_cache");
3302        if (cacheBaseDir == null) {
3303            return null;
3304        }
3305
3306        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3307        // This also serves to "GC" unused entries when the package cache version changes (which
3308        // can only happen during upgrades).
3309        if (isUpgrade) {
3310            FileUtils.deleteContents(cacheBaseDir);
3311        }
3312
3313
3314        // Return the versioned package cache directory. This is something like
3315        // "/data/system/package_cache/1"
3316        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3317
3318        // The following is a workaround to aid development on non-numbered userdebug
3319        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3320        // the system partition is newer.
3321        //
3322        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3323        // that starts with "eng." to signify that this is an engineering build and not
3324        // destined for release.
3325        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3326            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3327
3328            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3329            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3330            // in general and should not be used for production changes. In this specific case,
3331            // we know that they will work.
3332            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3333            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3334                FileUtils.deleteContents(cacheBaseDir);
3335                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3336            }
3337        }
3338
3339        return cacheDir;
3340    }
3341
3342    @Override
3343    public boolean isFirstBoot() {
3344        // allow instant applications
3345        return mFirstBoot;
3346    }
3347
3348    @Override
3349    public boolean isOnlyCoreApps() {
3350        // allow instant applications
3351        return mOnlyCore;
3352    }
3353
3354    @Override
3355    public boolean isUpgrade() {
3356        // allow instant applications
3357        return mIsUpgrade;
3358    }
3359
3360    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3361        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3362
3363        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3364                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3365                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3366        if (matches.size() == 1) {
3367            return matches.get(0).getComponentInfo().packageName;
3368        } else if (matches.size() == 0) {
3369            Log.e(TAG, "There should probably be a verifier, but, none were found");
3370            return null;
3371        }
3372        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3373    }
3374
3375    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3376        synchronized (mPackages) {
3377            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3378            if (libraryEntry == null) {
3379                throw new IllegalStateException("Missing required shared library:" + name);
3380            }
3381            return libraryEntry.apk;
3382        }
3383    }
3384
3385    private @NonNull String getRequiredInstallerLPr() {
3386        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3387        intent.addCategory(Intent.CATEGORY_DEFAULT);
3388        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3389
3390        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3391                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3392                UserHandle.USER_SYSTEM);
3393        if (matches.size() == 1) {
3394            ResolveInfo resolveInfo = matches.get(0);
3395            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3396                throw new RuntimeException("The installer must be a privileged app");
3397            }
3398            return matches.get(0).getComponentInfo().packageName;
3399        } else {
3400            throw new RuntimeException("There must be exactly one installer; found " + matches);
3401        }
3402    }
3403
3404    private @NonNull String getRequiredUninstallerLPr() {
3405        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3406        intent.addCategory(Intent.CATEGORY_DEFAULT);
3407        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3408
3409        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3410                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3411                UserHandle.USER_SYSTEM);
3412        if (resolveInfo == null ||
3413                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3414            throw new RuntimeException("There must be exactly one uninstaller; found "
3415                    + resolveInfo);
3416        }
3417        return resolveInfo.getComponentInfo().packageName;
3418    }
3419
3420    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3421        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3422
3423        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3424                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3425                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3426        ResolveInfo best = null;
3427        final int N = matches.size();
3428        for (int i = 0; i < N; i++) {
3429            final ResolveInfo cur = matches.get(i);
3430            final String packageName = cur.getComponentInfo().packageName;
3431            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3432                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3433                continue;
3434            }
3435
3436            if (best == null || cur.priority > best.priority) {
3437                best = cur;
3438            }
3439        }
3440
3441        if (best != null) {
3442            return best.getComponentInfo().getComponentName();
3443        }
3444        Slog.w(TAG, "Intent filter verifier not found");
3445        return null;
3446    }
3447
3448    @Override
3449    public @Nullable ComponentName getInstantAppResolverComponent() {
3450        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3451            return null;
3452        }
3453        synchronized (mPackages) {
3454            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3455            if (instantAppResolver == null) {
3456                return null;
3457            }
3458            return instantAppResolver.first;
3459        }
3460    }
3461
3462    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3463        final String[] packageArray =
3464                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3465        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3466            if (DEBUG_EPHEMERAL) {
3467                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3468            }
3469            return null;
3470        }
3471
3472        final int callingUid = Binder.getCallingUid();
3473        final int resolveFlags =
3474                MATCH_DIRECT_BOOT_AWARE
3475                | MATCH_DIRECT_BOOT_UNAWARE
3476                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3477        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3478        final Intent resolverIntent = new Intent(actionName);
3479        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3480                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3481        // temporarily look for the old action
3482        if (resolvers.size() == 0) {
3483            if (DEBUG_EPHEMERAL) {
3484                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3485            }
3486            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3487            resolverIntent.setAction(actionName);
3488            resolvers = queryIntentServicesInternal(resolverIntent, null,
3489                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3490        }
3491        final int N = resolvers.size();
3492        if (N == 0) {
3493            if (DEBUG_EPHEMERAL) {
3494                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3495            }
3496            return null;
3497        }
3498
3499        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3500        for (int i = 0; i < N; i++) {
3501            final ResolveInfo info = resolvers.get(i);
3502
3503            if (info.serviceInfo == null) {
3504                continue;
3505            }
3506
3507            final String packageName = info.serviceInfo.packageName;
3508            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3509                if (DEBUG_EPHEMERAL) {
3510                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3511                            + " pkg: " + packageName + ", info:" + info);
3512                }
3513                continue;
3514            }
3515
3516            if (DEBUG_EPHEMERAL) {
3517                Slog.v(TAG, "Ephemeral resolver found;"
3518                        + " pkg: " + packageName + ", info:" + info);
3519            }
3520            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3521        }
3522        if (DEBUG_EPHEMERAL) {
3523            Slog.v(TAG, "Ephemeral resolver NOT found");
3524        }
3525        return null;
3526    }
3527
3528    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3529        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3530        intent.addCategory(Intent.CATEGORY_DEFAULT);
3531        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3532
3533        final int resolveFlags =
3534                MATCH_DIRECT_BOOT_AWARE
3535                | MATCH_DIRECT_BOOT_UNAWARE
3536                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3537        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3538                resolveFlags, UserHandle.USER_SYSTEM);
3539        // temporarily look for the old action
3540        if (matches.isEmpty()) {
3541            if (DEBUG_EPHEMERAL) {
3542                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3543            }
3544            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3545            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3546                    resolveFlags, UserHandle.USER_SYSTEM);
3547        }
3548        Iterator<ResolveInfo> iter = matches.iterator();
3549        while (iter.hasNext()) {
3550            final ResolveInfo rInfo = iter.next();
3551            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3552            if (ps != null) {
3553                final PermissionsState permissionsState = ps.getPermissionsState();
3554                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3555                    continue;
3556                }
3557            }
3558            iter.remove();
3559        }
3560        if (matches.size() == 0) {
3561            return null;
3562        } else if (matches.size() == 1) {
3563            return (ActivityInfo) matches.get(0).getComponentInfo();
3564        } else {
3565            throw new RuntimeException(
3566                    "There must be at most one ephemeral installer; found " + matches);
3567        }
3568    }
3569
3570    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3571            @NonNull ComponentName resolver) {
3572        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3573                .addCategory(Intent.CATEGORY_DEFAULT)
3574                .setPackage(resolver.getPackageName());
3575        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3576        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3577                UserHandle.USER_SYSTEM);
3578        // temporarily look for the old action
3579        if (matches.isEmpty()) {
3580            if (DEBUG_EPHEMERAL) {
3581                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3582            }
3583            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3584            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3585                    UserHandle.USER_SYSTEM);
3586        }
3587        if (matches.isEmpty()) {
3588            return null;
3589        }
3590        return matches.get(0).getComponentInfo().getComponentName();
3591    }
3592
3593    private void primeDomainVerificationsLPw(int userId) {
3594        if (DEBUG_DOMAIN_VERIFICATION) {
3595            Slog.d(TAG, "Priming domain verifications in user " + userId);
3596        }
3597
3598        SystemConfig systemConfig = SystemConfig.getInstance();
3599        ArraySet<String> packages = systemConfig.getLinkedApps();
3600
3601        for (String packageName : packages) {
3602            PackageParser.Package pkg = mPackages.get(packageName);
3603            if (pkg != null) {
3604                if (!pkg.isSystemApp()) {
3605                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3606                    continue;
3607                }
3608
3609                ArraySet<String> domains = null;
3610                for (PackageParser.Activity a : pkg.activities) {
3611                    for (ActivityIntentInfo filter : a.intents) {
3612                        if (hasValidDomains(filter)) {
3613                            if (domains == null) {
3614                                domains = new ArraySet<String>();
3615                            }
3616                            domains.addAll(filter.getHostsList());
3617                        }
3618                    }
3619                }
3620
3621                if (domains != null && domains.size() > 0) {
3622                    if (DEBUG_DOMAIN_VERIFICATION) {
3623                        Slog.v(TAG, "      + " + packageName);
3624                    }
3625                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3626                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3627                    // and then 'always' in the per-user state actually used for intent resolution.
3628                    final IntentFilterVerificationInfo ivi;
3629                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3630                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3631                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3632                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3633                } else {
3634                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3635                            + "' does not handle web links");
3636                }
3637            } else {
3638                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3639            }
3640        }
3641
3642        scheduleWritePackageRestrictionsLocked(userId);
3643        scheduleWriteSettingsLocked();
3644    }
3645
3646    private void applyFactoryDefaultBrowserLPw(int userId) {
3647        // The default browser app's package name is stored in a string resource,
3648        // with a product-specific overlay used for vendor customization.
3649        String browserPkg = mContext.getResources().getString(
3650                com.android.internal.R.string.default_browser);
3651        if (!TextUtils.isEmpty(browserPkg)) {
3652            // non-empty string => required to be a known package
3653            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3654            if (ps == null) {
3655                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3656                browserPkg = null;
3657            } else {
3658                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3659            }
3660        }
3661
3662        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3663        // default.  If there's more than one, just leave everything alone.
3664        if (browserPkg == null) {
3665            calculateDefaultBrowserLPw(userId);
3666        }
3667    }
3668
3669    private void calculateDefaultBrowserLPw(int userId) {
3670        List<String> allBrowsers = resolveAllBrowserApps(userId);
3671        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3672        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3673    }
3674
3675    private List<String> resolveAllBrowserApps(int userId) {
3676        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3677        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3678                PackageManager.MATCH_ALL, userId);
3679
3680        final int count = list.size();
3681        List<String> result = new ArrayList<String>(count);
3682        for (int i=0; i<count; i++) {
3683            ResolveInfo info = list.get(i);
3684            if (info.activityInfo == null
3685                    || !info.handleAllWebDataURI
3686                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3687                    || result.contains(info.activityInfo.packageName)) {
3688                continue;
3689            }
3690            result.add(info.activityInfo.packageName);
3691        }
3692
3693        return result;
3694    }
3695
3696    private boolean packageIsBrowser(String packageName, int userId) {
3697        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3698                PackageManager.MATCH_ALL, userId);
3699        final int N = list.size();
3700        for (int i = 0; i < N; i++) {
3701            ResolveInfo info = list.get(i);
3702            if (packageName.equals(info.activityInfo.packageName)) {
3703                return true;
3704            }
3705        }
3706        return false;
3707    }
3708
3709    private void checkDefaultBrowser() {
3710        final int myUserId = UserHandle.myUserId();
3711        final String packageName = getDefaultBrowserPackageName(myUserId);
3712        if (packageName != null) {
3713            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3714            if (info == null) {
3715                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3716                synchronized (mPackages) {
3717                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3718                }
3719            }
3720        }
3721    }
3722
3723    @Override
3724    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3725            throws RemoteException {
3726        try {
3727            return super.onTransact(code, data, reply, flags);
3728        } catch (RuntimeException e) {
3729            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3730                Slog.wtf(TAG, "Package Manager Crash", e);
3731            }
3732            throw e;
3733        }
3734    }
3735
3736    static int[] appendInts(int[] cur, int[] add) {
3737        if (add == null) return cur;
3738        if (cur == null) return add;
3739        final int N = add.length;
3740        for (int i=0; i<N; i++) {
3741            cur = appendInt(cur, add[i]);
3742        }
3743        return cur;
3744    }
3745
3746    /**
3747     * Returns whether or not a full application can see an instant application.
3748     * <p>
3749     * Currently, there are three cases in which this can occur:
3750     * <ol>
3751     * <li>The calling application is a "special" process. The special
3752     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3753     *     and {@code 0}</li>
3754     * <li>The calling application has the permission
3755     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3756     * <li>The calling application is the default launcher on the
3757     *     system partition.</li>
3758     * </ol>
3759     */
3760    private boolean canViewInstantApps(int callingUid, int userId) {
3761        if (callingUid == Process.SYSTEM_UID
3762                || callingUid == Process.SHELL_UID
3763                || callingUid == Process.ROOT_UID) {
3764            return true;
3765        }
3766        if (mContext.checkCallingOrSelfPermission(
3767                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3768            return true;
3769        }
3770        if (mContext.checkCallingOrSelfPermission(
3771                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3772            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3773            if (homeComponent != null
3774                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3775                return true;
3776            }
3777        }
3778        return false;
3779    }
3780
3781    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3782        if (!sUserManager.exists(userId)) return null;
3783        if (ps == null) {
3784            return null;
3785        }
3786        PackageParser.Package p = ps.pkg;
3787        if (p == null) {
3788            return null;
3789        }
3790        final int callingUid = Binder.getCallingUid();
3791        // Filter out ephemeral app metadata:
3792        //   * The system/shell/root can see metadata for any app
3793        //   * An installed app can see metadata for 1) other installed apps
3794        //     and 2) ephemeral apps that have explicitly interacted with it
3795        //   * Ephemeral apps can only see their own data and exposed installed apps
3796        //   * Holding a signature permission allows seeing instant apps
3797        if (filterAppAccessLPr(ps, callingUid, userId)) {
3798            return null;
3799        }
3800
3801        final PermissionsState permissionsState = ps.getPermissionsState();
3802
3803        // Compute GIDs only if requested
3804        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3805                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3806        // Compute granted permissions only if package has requested permissions
3807        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3808                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3809        final PackageUserState state = ps.readUserState(userId);
3810
3811        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3812                && ps.isSystem()) {
3813            flags |= MATCH_ANY_USER;
3814        }
3815
3816        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3817                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3818
3819        if (packageInfo == null) {
3820            return null;
3821        }
3822
3823        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3824                resolveExternalPackageNameLPr(p);
3825
3826        return packageInfo;
3827    }
3828
3829    @Override
3830    public void checkPackageStartable(String packageName, int userId) {
3831        final int callingUid = Binder.getCallingUid();
3832        if (getInstantAppPackageName(callingUid) != null) {
3833            throw new SecurityException("Instant applications don't have access to this method");
3834        }
3835        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3836        synchronized (mPackages) {
3837            final PackageSetting ps = mSettings.mPackages.get(packageName);
3838            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3839                throw new SecurityException("Package " + packageName + " was not found!");
3840            }
3841
3842            if (!ps.getInstalled(userId)) {
3843                throw new SecurityException(
3844                        "Package " + packageName + " was not installed for user " + userId + "!");
3845            }
3846
3847            if (mSafeMode && !ps.isSystem()) {
3848                throw new SecurityException("Package " + packageName + " not a system app!");
3849            }
3850
3851            if (mFrozenPackages.contains(packageName)) {
3852                throw new SecurityException("Package " + packageName + " is currently frozen!");
3853            }
3854
3855            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3856                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3857                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3858            }
3859        }
3860    }
3861
3862    @Override
3863    public boolean isPackageAvailable(String packageName, int userId) {
3864        if (!sUserManager.exists(userId)) return false;
3865        final int callingUid = Binder.getCallingUid();
3866        enforceCrossUserPermission(callingUid, userId,
3867                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3868        synchronized (mPackages) {
3869            PackageParser.Package p = mPackages.get(packageName);
3870            if (p != null) {
3871                final PackageSetting ps = (PackageSetting) p.mExtras;
3872                if (filterAppAccessLPr(ps, callingUid, userId)) {
3873                    return false;
3874                }
3875                if (ps != null) {
3876                    final PackageUserState state = ps.readUserState(userId);
3877                    if (state != null) {
3878                        return PackageParser.isAvailable(state);
3879                    }
3880                }
3881            }
3882        }
3883        return false;
3884    }
3885
3886    @Override
3887    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3888        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3889                flags, Binder.getCallingUid(), userId);
3890    }
3891
3892    @Override
3893    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3894            int flags, int userId) {
3895        return getPackageInfoInternal(versionedPackage.getPackageName(),
3896                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3897    }
3898
3899    /**
3900     * Important: The provided filterCallingUid is used exclusively to filter out packages
3901     * that can be seen based on user state. It's typically the original caller uid prior
3902     * to clearing. Because it can only be provided by trusted code, it's value can be
3903     * trusted and will be used as-is; unlike userId which will be validated by this method.
3904     */
3905    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3906            int flags, int filterCallingUid, int userId) {
3907        if (!sUserManager.exists(userId)) return null;
3908        flags = updateFlagsForPackage(flags, userId, packageName);
3909        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3910                false /* requireFullPermission */, false /* checkShell */, "get package info");
3911
3912        // reader
3913        synchronized (mPackages) {
3914            // Normalize package name to handle renamed packages and static libs
3915            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3916
3917            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3918            if (matchFactoryOnly) {
3919                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3920                if (ps != null) {
3921                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3922                        return null;
3923                    }
3924                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3925                        return null;
3926                    }
3927                    return generatePackageInfo(ps, flags, userId);
3928                }
3929            }
3930
3931            PackageParser.Package p = mPackages.get(packageName);
3932            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3933                return null;
3934            }
3935            if (DEBUG_PACKAGE_INFO)
3936                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3937            if (p != null) {
3938                final PackageSetting ps = (PackageSetting) p.mExtras;
3939                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3940                    return null;
3941                }
3942                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3943                    return null;
3944                }
3945                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3946            }
3947            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3948                final PackageSetting ps = mSettings.mPackages.get(packageName);
3949                if (ps == null) return null;
3950                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3951                    return null;
3952                }
3953                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3954                    return null;
3955                }
3956                return generatePackageInfo(ps, flags, userId);
3957            }
3958        }
3959        return null;
3960    }
3961
3962    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3963        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3964            return true;
3965        }
3966        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3967            return true;
3968        }
3969        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3970            return true;
3971        }
3972        return false;
3973    }
3974
3975    private boolean isComponentVisibleToInstantApp(
3976            @Nullable ComponentName component, @ComponentType int type) {
3977        if (type == TYPE_ACTIVITY) {
3978            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3979            return activity != null
3980                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3981                    : false;
3982        } else if (type == TYPE_RECEIVER) {
3983            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3984            return activity != null
3985                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3986                    : false;
3987        } else if (type == TYPE_SERVICE) {
3988            final PackageParser.Service service = mServices.mServices.get(component);
3989            return service != null
3990                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3991                    : false;
3992        } else if (type == TYPE_PROVIDER) {
3993            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3994            return provider != null
3995                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3996                    : false;
3997        } else if (type == TYPE_UNKNOWN) {
3998            return isComponentVisibleToInstantApp(component);
3999        }
4000        return false;
4001    }
4002
4003    /**
4004     * Returns whether or not access to the application should be filtered.
4005     * <p>
4006     * Access may be limited based upon whether the calling or target applications
4007     * are instant applications.
4008     *
4009     * @see #canAccessInstantApps(int)
4010     */
4011    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4012            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4013        // if we're in an isolated process, get the real calling UID
4014        if (Process.isIsolated(callingUid)) {
4015            callingUid = mIsolatedOwners.get(callingUid);
4016        }
4017        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4018        final boolean callerIsInstantApp = instantAppPkgName != null;
4019        if (ps == null) {
4020            if (callerIsInstantApp) {
4021                // pretend the application exists, but, needs to be filtered
4022                return true;
4023            }
4024            return false;
4025        }
4026        // if the target and caller are the same application, don't filter
4027        if (isCallerSameApp(ps.name, callingUid)) {
4028            return false;
4029        }
4030        if (callerIsInstantApp) {
4031            // request for a specific component; if it hasn't been explicitly exposed, filter
4032            if (component != null) {
4033                return !isComponentVisibleToInstantApp(component, componentType);
4034            }
4035            // request for application; if no components have been explicitly exposed, filter
4036            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4037        }
4038        if (ps.getInstantApp(userId)) {
4039            // caller can see all components of all instant applications, don't filter
4040            if (canViewInstantApps(callingUid, userId)) {
4041                return false;
4042            }
4043            // request for a specific instant application component, filter
4044            if (component != null) {
4045                return true;
4046            }
4047            // request for an instant application; if the caller hasn't been granted access, filter
4048            return !mInstantAppRegistry.isInstantAccessGranted(
4049                    userId, UserHandle.getAppId(callingUid), ps.appId);
4050        }
4051        return false;
4052    }
4053
4054    /**
4055     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4056     */
4057    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4058        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4059    }
4060
4061    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4062            int flags) {
4063        // Callers can access only the libs they depend on, otherwise they need to explicitly
4064        // ask for the shared libraries given the caller is allowed to access all static libs.
4065        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4066            // System/shell/root get to see all static libs
4067            final int appId = UserHandle.getAppId(uid);
4068            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4069                    || appId == Process.ROOT_UID) {
4070                return false;
4071            }
4072        }
4073
4074        // No package means no static lib as it is always on internal storage
4075        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4076            return false;
4077        }
4078
4079        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4080                ps.pkg.staticSharedLibVersion);
4081        if (libEntry == null) {
4082            return false;
4083        }
4084
4085        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4086        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4087        if (uidPackageNames == null) {
4088            return true;
4089        }
4090
4091        for (String uidPackageName : uidPackageNames) {
4092            if (ps.name.equals(uidPackageName)) {
4093                return false;
4094            }
4095            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4096            if (uidPs != null) {
4097                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4098                        libEntry.info.getName());
4099                if (index < 0) {
4100                    continue;
4101                }
4102                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4103                    return false;
4104                }
4105            }
4106        }
4107        return true;
4108    }
4109
4110    @Override
4111    public String[] currentToCanonicalPackageNames(String[] names) {
4112        final int callingUid = Binder.getCallingUid();
4113        if (getInstantAppPackageName(callingUid) != null) {
4114            return names;
4115        }
4116        final String[] out = new String[names.length];
4117        // reader
4118        synchronized (mPackages) {
4119            final int callingUserId = UserHandle.getUserId(callingUid);
4120            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4121            for (int i=names.length-1; i>=0; i--) {
4122                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4123                boolean translateName = false;
4124                if (ps != null && ps.realName != null) {
4125                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4126                    translateName = !targetIsInstantApp
4127                            || canViewInstantApps
4128                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4129                                    UserHandle.getAppId(callingUid), ps.appId);
4130                }
4131                out[i] = translateName ? ps.realName : names[i];
4132            }
4133        }
4134        return out;
4135    }
4136
4137    @Override
4138    public String[] canonicalToCurrentPackageNames(String[] names) {
4139        final int callingUid = Binder.getCallingUid();
4140        if (getInstantAppPackageName(callingUid) != null) {
4141            return names;
4142        }
4143        final String[] out = new String[names.length];
4144        // reader
4145        synchronized (mPackages) {
4146            final int callingUserId = UserHandle.getUserId(callingUid);
4147            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4148            for (int i=names.length-1; i>=0; i--) {
4149                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4150                boolean translateName = false;
4151                if (cur != null) {
4152                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4153                    final boolean targetIsInstantApp =
4154                            ps != null && ps.getInstantApp(callingUserId);
4155                    translateName = !targetIsInstantApp
4156                            || canViewInstantApps
4157                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4158                                    UserHandle.getAppId(callingUid), ps.appId);
4159                }
4160                out[i] = translateName ? cur : names[i];
4161            }
4162        }
4163        return out;
4164    }
4165
4166    @Override
4167    public int getPackageUid(String packageName, int flags, int userId) {
4168        if (!sUserManager.exists(userId)) return -1;
4169        final int callingUid = Binder.getCallingUid();
4170        flags = updateFlagsForPackage(flags, userId, packageName);
4171        enforceCrossUserPermission(callingUid, userId,
4172                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4173
4174        // reader
4175        synchronized (mPackages) {
4176            final PackageParser.Package p = mPackages.get(packageName);
4177            if (p != null && p.isMatch(flags)) {
4178                PackageSetting ps = (PackageSetting) p.mExtras;
4179                if (filterAppAccessLPr(ps, callingUid, userId)) {
4180                    return -1;
4181                }
4182                return UserHandle.getUid(userId, p.applicationInfo.uid);
4183            }
4184            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4185                final PackageSetting ps = mSettings.mPackages.get(packageName);
4186                if (ps != null && ps.isMatch(flags)
4187                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4188                    return UserHandle.getUid(userId, ps.appId);
4189                }
4190            }
4191        }
4192
4193        return -1;
4194    }
4195
4196    @Override
4197    public int[] getPackageGids(String packageName, int flags, int userId) {
4198        if (!sUserManager.exists(userId)) return null;
4199        final int callingUid = Binder.getCallingUid();
4200        flags = updateFlagsForPackage(flags, userId, packageName);
4201        enforceCrossUserPermission(callingUid, userId,
4202                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4203
4204        // reader
4205        synchronized (mPackages) {
4206            final PackageParser.Package p = mPackages.get(packageName);
4207            if (p != null && p.isMatch(flags)) {
4208                PackageSetting ps = (PackageSetting) p.mExtras;
4209                if (filterAppAccessLPr(ps, callingUid, userId)) {
4210                    return null;
4211                }
4212                // TODO: Shouldn't this be checking for package installed state for userId and
4213                // return null?
4214                return ps.getPermissionsState().computeGids(userId);
4215            }
4216            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4217                final PackageSetting ps = mSettings.mPackages.get(packageName);
4218                if (ps != null && ps.isMatch(flags)
4219                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4220                    return ps.getPermissionsState().computeGids(userId);
4221                }
4222            }
4223        }
4224
4225        return null;
4226    }
4227
4228    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
4229        if (bp.perm != null) {
4230            return PackageParser.generatePermissionInfo(bp.perm, flags);
4231        }
4232        PermissionInfo pi = new PermissionInfo();
4233        pi.name = bp.name;
4234        pi.packageName = bp.sourcePackage;
4235        pi.nonLocalizedLabel = bp.name;
4236        pi.protectionLevel = bp.protectionLevel;
4237        return pi;
4238    }
4239
4240    @Override
4241    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4242        final int callingUid = Binder.getCallingUid();
4243        if (getInstantAppPackageName(callingUid) != null) {
4244            return null;
4245        }
4246        // reader
4247        synchronized (mPackages) {
4248            final BasePermission p = mSettings.mPermissions.get(name);
4249            if (p == null) {
4250                return null;
4251            }
4252            // If the caller is an app that targets pre 26 SDK drop protection flags.
4253            final PermissionInfo permissionInfo = generatePermissionInfo(p, flags);
4254            if (permissionInfo != null) {
4255                permissionInfo.protectionLevel = adjustPermissionProtectionFlagsLPr(
4256                        permissionInfo.protectionLevel, packageName, callingUid);
4257            }
4258            return permissionInfo;
4259        }
4260    }
4261
4262    private int adjustPermissionProtectionFlagsLPr(int protectionLevel,
4263            String packageName, int uid) {
4264        // Signature permission flags area always reported
4265        final int protectionLevelMasked = protectionLevel
4266                & (PermissionInfo.PROTECTION_NORMAL
4267                | PermissionInfo.PROTECTION_DANGEROUS
4268                | PermissionInfo.PROTECTION_SIGNATURE);
4269        if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
4270            return protectionLevel;
4271        }
4272
4273        // System sees all flags.
4274        final int appId = UserHandle.getAppId(uid);
4275        if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
4276                || appId == Process.SHELL_UID) {
4277            return protectionLevel;
4278        }
4279
4280        // Normalize package name to handle renamed packages and static libs
4281        packageName = resolveInternalPackageNameLPr(packageName,
4282                PackageManager.VERSION_CODE_HIGHEST);
4283
4284        // Apps that target O see flags for all protection levels.
4285        final PackageSetting ps = mSettings.mPackages.get(packageName);
4286        if (ps == null) {
4287            return protectionLevel;
4288        }
4289        if (ps.appId != appId) {
4290            return protectionLevel;
4291        }
4292
4293        final PackageParser.Package pkg = mPackages.get(packageName);
4294        if (pkg == null) {
4295            return protectionLevel;
4296        }
4297        if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
4298            return protectionLevelMasked;
4299        }
4300
4301        return protectionLevel;
4302    }
4303
4304    @Override
4305    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4306            int flags) {
4307        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4308            return null;
4309        }
4310        // reader
4311        synchronized (mPackages) {
4312            if (group != null && !mPermissionGroups.containsKey(group)) {
4313                // This is thrown as NameNotFoundException
4314                return null;
4315            }
4316
4317            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4318            for (BasePermission p : mSettings.mPermissions.values()) {
4319                if (group == null) {
4320                    if (p.perm == null || p.perm.info.group == null) {
4321                        out.add(generatePermissionInfo(p, flags));
4322                    }
4323                } else {
4324                    if (p.perm != null && group.equals(p.perm.info.group)) {
4325                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4326                    }
4327                }
4328            }
4329            return new ParceledListSlice<>(out);
4330        }
4331    }
4332
4333    @Override
4334    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4335        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4336            return null;
4337        }
4338        // reader
4339        synchronized (mPackages) {
4340            return PackageParser.generatePermissionGroupInfo(
4341                    mPermissionGroups.get(name), flags);
4342        }
4343    }
4344
4345    @Override
4346    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4347        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4348            return ParceledListSlice.emptyList();
4349        }
4350        // reader
4351        synchronized (mPackages) {
4352            final int N = mPermissionGroups.size();
4353            ArrayList<PermissionGroupInfo> out
4354                    = new ArrayList<PermissionGroupInfo>(N);
4355            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4356                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4357            }
4358            return new ParceledListSlice<>(out);
4359        }
4360    }
4361
4362    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4363            int filterCallingUid, int userId) {
4364        if (!sUserManager.exists(userId)) return null;
4365        PackageSetting ps = mSettings.mPackages.get(packageName);
4366        if (ps != null) {
4367            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4368                return null;
4369            }
4370            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4371                return null;
4372            }
4373            if (ps.pkg == null) {
4374                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4375                if (pInfo != null) {
4376                    return pInfo.applicationInfo;
4377                }
4378                return null;
4379            }
4380            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4381                    ps.readUserState(userId), userId);
4382            if (ai != null) {
4383                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4384            }
4385            return ai;
4386        }
4387        return null;
4388    }
4389
4390    @Override
4391    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4392        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4393    }
4394
4395    /**
4396     * Important: The provided filterCallingUid is used exclusively to filter out applications
4397     * that can be seen based on user state. It's typically the original caller uid prior
4398     * to clearing. Because it can only be provided by trusted code, it's value can be
4399     * trusted and will be used as-is; unlike userId which will be validated by this method.
4400     */
4401    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4402            int filterCallingUid, int userId) {
4403        if (!sUserManager.exists(userId)) return null;
4404        flags = updateFlagsForApplication(flags, userId, packageName);
4405        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4406                false /* requireFullPermission */, false /* checkShell */, "get application info");
4407
4408        // writer
4409        synchronized (mPackages) {
4410            // Normalize package name to handle renamed packages and static libs
4411            packageName = resolveInternalPackageNameLPr(packageName,
4412                    PackageManager.VERSION_CODE_HIGHEST);
4413
4414            PackageParser.Package p = mPackages.get(packageName);
4415            if (DEBUG_PACKAGE_INFO) Log.v(
4416                    TAG, "getApplicationInfo " + packageName
4417                    + ": " + p);
4418            if (p != null) {
4419                PackageSetting ps = mSettings.mPackages.get(packageName);
4420                if (ps == null) return null;
4421                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4422                    return null;
4423                }
4424                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4425                    return null;
4426                }
4427                // Note: isEnabledLP() does not apply here - always return info
4428                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4429                        p, flags, ps.readUserState(userId), userId);
4430                if (ai != null) {
4431                    ai.packageName = resolveExternalPackageNameLPr(p);
4432                }
4433                return ai;
4434            }
4435            if ("android".equals(packageName)||"system".equals(packageName)) {
4436                return mAndroidApplication;
4437            }
4438            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4439                // Already generates the external package name
4440                return generateApplicationInfoFromSettingsLPw(packageName,
4441                        flags, filterCallingUid, userId);
4442            }
4443        }
4444        return null;
4445    }
4446
4447    private String normalizePackageNameLPr(String packageName) {
4448        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4449        return normalizedPackageName != null ? normalizedPackageName : packageName;
4450    }
4451
4452    @Override
4453    public void deletePreloadsFileCache() {
4454        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4455            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4456        }
4457        File dir = Environment.getDataPreloadsFileCacheDirectory();
4458        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4459        FileUtils.deleteContents(dir);
4460    }
4461
4462    @Override
4463    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4464            final int storageFlags, final IPackageDataObserver observer) {
4465        mContext.enforceCallingOrSelfPermission(
4466                android.Manifest.permission.CLEAR_APP_CACHE, null);
4467        mHandler.post(() -> {
4468            boolean success = false;
4469            try {
4470                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4471                success = true;
4472            } catch (IOException e) {
4473                Slog.w(TAG, e);
4474            }
4475            if (observer != null) {
4476                try {
4477                    observer.onRemoveCompleted(null, success);
4478                } catch (RemoteException e) {
4479                    Slog.w(TAG, e);
4480                }
4481            }
4482        });
4483    }
4484
4485    @Override
4486    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4487            final int storageFlags, final IntentSender pi) {
4488        mContext.enforceCallingOrSelfPermission(
4489                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4490        mHandler.post(() -> {
4491            boolean success = false;
4492            try {
4493                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4494                success = true;
4495            } catch (IOException e) {
4496                Slog.w(TAG, e);
4497            }
4498            if (pi != null) {
4499                try {
4500                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4501                } catch (SendIntentException e) {
4502                    Slog.w(TAG, e);
4503                }
4504            }
4505        });
4506    }
4507
4508    /**
4509     * Blocking call to clear various types of cached data across the system
4510     * until the requested bytes are available.
4511     */
4512    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4513        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4514        final File file = storage.findPathForUuid(volumeUuid);
4515        if (file.getUsableSpace() >= bytes) return;
4516
4517        if (ENABLE_FREE_CACHE_V2) {
4518            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4519                    volumeUuid);
4520            final boolean aggressive = (storageFlags
4521                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4522            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4523
4524            // 1. Pre-flight to determine if we have any chance to succeed
4525            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4526            if (internalVolume && (aggressive || SystemProperties
4527                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4528                deletePreloadsFileCache();
4529                if (file.getUsableSpace() >= bytes) return;
4530            }
4531
4532            // 3. Consider parsed APK data (aggressive only)
4533            if (internalVolume && aggressive) {
4534                FileUtils.deleteContents(mCacheDir);
4535                if (file.getUsableSpace() >= bytes) return;
4536            }
4537
4538            // 4. Consider cached app data (above quotas)
4539            try {
4540                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4541                        Installer.FLAG_FREE_CACHE_V2);
4542            } catch (InstallerException ignored) {
4543            }
4544            if (file.getUsableSpace() >= bytes) return;
4545
4546            // 5. Consider shared libraries with refcount=0 and age>min cache period
4547            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4548                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4549                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4550                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4551                return;
4552            }
4553
4554            // 6. Consider dexopt output (aggressive only)
4555            // TODO: Implement
4556
4557            // 7. Consider installed instant apps unused longer than min cache period
4558            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4559                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4560                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4561                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4562                return;
4563            }
4564
4565            // 8. Consider cached app data (below quotas)
4566            try {
4567                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4568                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4569            } catch (InstallerException ignored) {
4570            }
4571            if (file.getUsableSpace() >= bytes) return;
4572
4573            // 9. Consider DropBox entries
4574            // TODO: Implement
4575
4576            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4577            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4578                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4579                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4580                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4581                return;
4582            }
4583        } else {
4584            try {
4585                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4586            } catch (InstallerException ignored) {
4587            }
4588            if (file.getUsableSpace() >= bytes) return;
4589        }
4590
4591        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4592    }
4593
4594    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4595            throws IOException {
4596        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4597        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4598
4599        List<VersionedPackage> packagesToDelete = null;
4600        final long now = System.currentTimeMillis();
4601
4602        synchronized (mPackages) {
4603            final int[] allUsers = sUserManager.getUserIds();
4604            final int libCount = mSharedLibraries.size();
4605            for (int i = 0; i < libCount; i++) {
4606                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4607                if (versionedLib == null) {
4608                    continue;
4609                }
4610                final int versionCount = versionedLib.size();
4611                for (int j = 0; j < versionCount; j++) {
4612                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4613                    // Skip packages that are not static shared libs.
4614                    if (!libInfo.isStatic()) {
4615                        break;
4616                    }
4617                    // Important: We skip static shared libs used for some user since
4618                    // in such a case we need to keep the APK on the device. The check for
4619                    // a lib being used for any user is performed by the uninstall call.
4620                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4621                    // Resolve the package name - we use synthetic package names internally
4622                    final String internalPackageName = resolveInternalPackageNameLPr(
4623                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4624                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4625                    // Skip unused static shared libs cached less than the min period
4626                    // to prevent pruning a lib needed by a subsequently installed package.
4627                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4628                        continue;
4629                    }
4630                    if (packagesToDelete == null) {
4631                        packagesToDelete = new ArrayList<>();
4632                    }
4633                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4634                            declaringPackage.getVersionCode()));
4635                }
4636            }
4637        }
4638
4639        if (packagesToDelete != null) {
4640            final int packageCount = packagesToDelete.size();
4641            for (int i = 0; i < packageCount; i++) {
4642                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4643                // Delete the package synchronously (will fail of the lib used for any user).
4644                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4645                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4646                                == PackageManager.DELETE_SUCCEEDED) {
4647                    if (volume.getUsableSpace() >= neededSpace) {
4648                        return true;
4649                    }
4650                }
4651            }
4652        }
4653
4654        return false;
4655    }
4656
4657    /**
4658     * Update given flags based on encryption status of current user.
4659     */
4660    private int updateFlags(int flags, int userId) {
4661        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4662                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4663            // Caller expressed an explicit opinion about what encryption
4664            // aware/unaware components they want to see, so fall through and
4665            // give them what they want
4666        } else {
4667            // Caller expressed no opinion, so match based on user state
4668            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4669                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4670            } else {
4671                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4672            }
4673        }
4674        return flags;
4675    }
4676
4677    private UserManagerInternal getUserManagerInternal() {
4678        if (mUserManagerInternal == null) {
4679            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4680        }
4681        return mUserManagerInternal;
4682    }
4683
4684    private DeviceIdleController.LocalService getDeviceIdleController() {
4685        if (mDeviceIdleController == null) {
4686            mDeviceIdleController =
4687                    LocalServices.getService(DeviceIdleController.LocalService.class);
4688        }
4689        return mDeviceIdleController;
4690    }
4691
4692    /**
4693     * Update given flags when being used to request {@link PackageInfo}.
4694     */
4695    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4696        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4697        boolean triaged = true;
4698        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4699                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4700            // Caller is asking for component details, so they'd better be
4701            // asking for specific encryption matching behavior, or be triaged
4702            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4703                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4704                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4705                triaged = false;
4706            }
4707        }
4708        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4709                | PackageManager.MATCH_SYSTEM_ONLY
4710                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4711            triaged = false;
4712        }
4713        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4714            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4715                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4716                    + Debug.getCallers(5));
4717        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4718                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4719            // If the caller wants all packages and has a restricted profile associated with it,
4720            // then match all users. This is to make sure that launchers that need to access work
4721            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4722            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4723            flags |= PackageManager.MATCH_ANY_USER;
4724        }
4725        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4726            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4727                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4728        }
4729        return updateFlags(flags, userId);
4730    }
4731
4732    /**
4733     * Update given flags when being used to request {@link ApplicationInfo}.
4734     */
4735    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4736        return updateFlagsForPackage(flags, userId, cookie);
4737    }
4738
4739    /**
4740     * Update given flags when being used to request {@link ComponentInfo}.
4741     */
4742    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4743        if (cookie instanceof Intent) {
4744            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4745                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4746            }
4747        }
4748
4749        boolean triaged = true;
4750        // Caller is asking for component details, so they'd better be
4751        // asking for specific encryption matching behavior, or be triaged
4752        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4753                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4754                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4755            triaged = false;
4756        }
4757        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4758            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4759                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4760        }
4761
4762        return updateFlags(flags, userId);
4763    }
4764
4765    /**
4766     * Update given intent when being used to request {@link ResolveInfo}.
4767     */
4768    private Intent updateIntentForResolve(Intent intent) {
4769        if (intent.getSelector() != null) {
4770            intent = intent.getSelector();
4771        }
4772        if (DEBUG_PREFERRED) {
4773            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4774        }
4775        return intent;
4776    }
4777
4778    /**
4779     * Update given flags when being used to request {@link ResolveInfo}.
4780     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4781     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4782     * flag set. However, this flag is only honoured in three circumstances:
4783     * <ul>
4784     * <li>when called from a system process</li>
4785     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4786     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4787     * action and a {@code android.intent.category.BROWSABLE} category</li>
4788     * </ul>
4789     */
4790    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4791        return updateFlagsForResolve(flags, userId, intent, callingUid,
4792                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4793    }
4794    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4795            boolean wantInstantApps) {
4796        return updateFlagsForResolve(flags, userId, intent, callingUid,
4797                wantInstantApps, false /*onlyExposedExplicitly*/);
4798    }
4799    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4800            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4801        // Safe mode means we shouldn't match any third-party components
4802        if (mSafeMode) {
4803            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4804        }
4805        if (getInstantAppPackageName(callingUid) != null) {
4806            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4807            if (onlyExposedExplicitly) {
4808                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4809            }
4810            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4811            flags |= PackageManager.MATCH_INSTANT;
4812        } else {
4813            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4814            final boolean allowMatchInstant =
4815                    (wantInstantApps
4816                            && Intent.ACTION_VIEW.equals(intent.getAction())
4817                            && hasWebURI(intent))
4818                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4819            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4820                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4821            if (!allowMatchInstant) {
4822                flags &= ~PackageManager.MATCH_INSTANT;
4823            }
4824        }
4825        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4826    }
4827
4828    @Override
4829    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4830        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4831    }
4832
4833    /**
4834     * Important: The provided filterCallingUid is used exclusively to filter out activities
4835     * that can be seen based on user state. It's typically the original caller uid prior
4836     * to clearing. Because it can only be provided by trusted code, it's value can be
4837     * trusted and will be used as-is; unlike userId which will be validated by this method.
4838     */
4839    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4840            int filterCallingUid, int userId) {
4841        if (!sUserManager.exists(userId)) return null;
4842        flags = updateFlagsForComponent(flags, userId, component);
4843        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4844                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4845        synchronized (mPackages) {
4846            PackageParser.Activity a = mActivities.mActivities.get(component);
4847
4848            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4849            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4850                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4851                if (ps == null) return null;
4852                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4853                    return null;
4854                }
4855                return PackageParser.generateActivityInfo(
4856                        a, flags, ps.readUserState(userId), userId);
4857            }
4858            if (mResolveComponentName.equals(component)) {
4859                return PackageParser.generateActivityInfo(
4860                        mResolveActivity, flags, new PackageUserState(), userId);
4861            }
4862        }
4863        return null;
4864    }
4865
4866    @Override
4867    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4868            String resolvedType) {
4869        synchronized (mPackages) {
4870            if (component.equals(mResolveComponentName)) {
4871                // The resolver supports EVERYTHING!
4872                return true;
4873            }
4874            final int callingUid = Binder.getCallingUid();
4875            final int callingUserId = UserHandle.getUserId(callingUid);
4876            PackageParser.Activity a = mActivities.mActivities.get(component);
4877            if (a == null) {
4878                return false;
4879            }
4880            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4881            if (ps == null) {
4882                return false;
4883            }
4884            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4885                return false;
4886            }
4887            for (int i=0; i<a.intents.size(); i++) {
4888                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4889                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4890                    return true;
4891                }
4892            }
4893            return false;
4894        }
4895    }
4896
4897    @Override
4898    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4899        if (!sUserManager.exists(userId)) return null;
4900        final int callingUid = Binder.getCallingUid();
4901        flags = updateFlagsForComponent(flags, userId, component);
4902        enforceCrossUserPermission(callingUid, userId,
4903                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4904        synchronized (mPackages) {
4905            PackageParser.Activity a = mReceivers.mActivities.get(component);
4906            if (DEBUG_PACKAGE_INFO) Log.v(
4907                TAG, "getReceiverInfo " + component + ": " + a);
4908            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4909                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4910                if (ps == null) return null;
4911                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4912                    return null;
4913                }
4914                return PackageParser.generateActivityInfo(
4915                        a, flags, ps.readUserState(userId), userId);
4916            }
4917        }
4918        return null;
4919    }
4920
4921    @Override
4922    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4923            int flags, int userId) {
4924        if (!sUserManager.exists(userId)) return null;
4925        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4926        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4927            return null;
4928        }
4929
4930        flags = updateFlagsForPackage(flags, userId, null);
4931
4932        final boolean canSeeStaticLibraries =
4933                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4934                        == PERMISSION_GRANTED
4935                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4936                        == PERMISSION_GRANTED
4937                || canRequestPackageInstallsInternal(packageName,
4938                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4939                        false  /* throwIfPermNotDeclared*/)
4940                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4941                        == PERMISSION_GRANTED;
4942
4943        synchronized (mPackages) {
4944            List<SharedLibraryInfo> result = null;
4945
4946            final int libCount = mSharedLibraries.size();
4947            for (int i = 0; i < libCount; i++) {
4948                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4949                if (versionedLib == null) {
4950                    continue;
4951                }
4952
4953                final int versionCount = versionedLib.size();
4954                for (int j = 0; j < versionCount; j++) {
4955                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4956                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4957                        break;
4958                    }
4959                    final long identity = Binder.clearCallingIdentity();
4960                    try {
4961                        PackageInfo packageInfo = getPackageInfoVersioned(
4962                                libInfo.getDeclaringPackage(), flags
4963                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4964                        if (packageInfo == null) {
4965                            continue;
4966                        }
4967                    } finally {
4968                        Binder.restoreCallingIdentity(identity);
4969                    }
4970
4971                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4972                            libInfo.getVersion(), libInfo.getType(),
4973                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4974                            flags, userId));
4975
4976                    if (result == null) {
4977                        result = new ArrayList<>();
4978                    }
4979                    result.add(resLibInfo);
4980                }
4981            }
4982
4983            return result != null ? new ParceledListSlice<>(result) : null;
4984        }
4985    }
4986
4987    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4988            SharedLibraryInfo libInfo, int flags, int userId) {
4989        List<VersionedPackage> versionedPackages = null;
4990        final int packageCount = mSettings.mPackages.size();
4991        for (int i = 0; i < packageCount; i++) {
4992            PackageSetting ps = mSettings.mPackages.valueAt(i);
4993
4994            if (ps == null) {
4995                continue;
4996            }
4997
4998            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4999                continue;
5000            }
5001
5002            final String libName = libInfo.getName();
5003            if (libInfo.isStatic()) {
5004                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5005                if (libIdx < 0) {
5006                    continue;
5007                }
5008                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
5009                    continue;
5010                }
5011                if (versionedPackages == null) {
5012                    versionedPackages = new ArrayList<>();
5013                }
5014                // If the dependent is a static shared lib, use the public package name
5015                String dependentPackageName = ps.name;
5016                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5017                    dependentPackageName = ps.pkg.manifestPackageName;
5018                }
5019                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5020            } else if (ps.pkg != null) {
5021                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5022                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5023                    if (versionedPackages == null) {
5024                        versionedPackages = new ArrayList<>();
5025                    }
5026                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5027                }
5028            }
5029        }
5030
5031        return versionedPackages;
5032    }
5033
5034    @Override
5035    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5036        if (!sUserManager.exists(userId)) return null;
5037        final int callingUid = Binder.getCallingUid();
5038        flags = updateFlagsForComponent(flags, userId, component);
5039        enforceCrossUserPermission(callingUid, userId,
5040                false /* requireFullPermission */, false /* checkShell */, "get service info");
5041        synchronized (mPackages) {
5042            PackageParser.Service s = mServices.mServices.get(component);
5043            if (DEBUG_PACKAGE_INFO) Log.v(
5044                TAG, "getServiceInfo " + component + ": " + s);
5045            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5046                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5047                if (ps == null) return null;
5048                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5049                    return null;
5050                }
5051                return PackageParser.generateServiceInfo(
5052                        s, flags, ps.readUserState(userId), userId);
5053            }
5054        }
5055        return null;
5056    }
5057
5058    @Override
5059    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5060        if (!sUserManager.exists(userId)) return null;
5061        final int callingUid = Binder.getCallingUid();
5062        flags = updateFlagsForComponent(flags, userId, component);
5063        enforceCrossUserPermission(callingUid, userId,
5064                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5065        synchronized (mPackages) {
5066            PackageParser.Provider p = mProviders.mProviders.get(component);
5067            if (DEBUG_PACKAGE_INFO) Log.v(
5068                TAG, "getProviderInfo " + component + ": " + p);
5069            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5070                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5071                if (ps == null) return null;
5072                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5073                    return null;
5074                }
5075                return PackageParser.generateProviderInfo(
5076                        p, flags, ps.readUserState(userId), userId);
5077            }
5078        }
5079        return null;
5080    }
5081
5082    @Override
5083    public String[] getSystemSharedLibraryNames() {
5084        // allow instant applications
5085        synchronized (mPackages) {
5086            Set<String> libs = null;
5087            final int libCount = mSharedLibraries.size();
5088            for (int i = 0; i < libCount; i++) {
5089                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5090                if (versionedLib == null) {
5091                    continue;
5092                }
5093                final int versionCount = versionedLib.size();
5094                for (int j = 0; j < versionCount; j++) {
5095                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5096                    if (!libEntry.info.isStatic()) {
5097                        if (libs == null) {
5098                            libs = new ArraySet<>();
5099                        }
5100                        libs.add(libEntry.info.getName());
5101                        break;
5102                    }
5103                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5104                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5105                            UserHandle.getUserId(Binder.getCallingUid()),
5106                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5107                        if (libs == null) {
5108                            libs = new ArraySet<>();
5109                        }
5110                        libs.add(libEntry.info.getName());
5111                        break;
5112                    }
5113                }
5114            }
5115
5116            if (libs != null) {
5117                String[] libsArray = new String[libs.size()];
5118                libs.toArray(libsArray);
5119                return libsArray;
5120            }
5121
5122            return null;
5123        }
5124    }
5125
5126    @Override
5127    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5128        // allow instant applications
5129        synchronized (mPackages) {
5130            return mServicesSystemSharedLibraryPackageName;
5131        }
5132    }
5133
5134    @Override
5135    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5136        // allow instant applications
5137        synchronized (mPackages) {
5138            return mSharedSystemSharedLibraryPackageName;
5139        }
5140    }
5141
5142    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5143        for (int i = userList.length - 1; i >= 0; --i) {
5144            final int userId = userList[i];
5145            // don't add instant app to the list of updates
5146            if (pkgSetting.getInstantApp(userId)) {
5147                continue;
5148            }
5149            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5150            if (changedPackages == null) {
5151                changedPackages = new SparseArray<>();
5152                mChangedPackages.put(userId, changedPackages);
5153            }
5154            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5155            if (sequenceNumbers == null) {
5156                sequenceNumbers = new HashMap<>();
5157                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5158            }
5159            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5160            if (sequenceNumber != null) {
5161                changedPackages.remove(sequenceNumber);
5162            }
5163            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5164            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5165        }
5166        mChangedPackagesSequenceNumber++;
5167    }
5168
5169    @Override
5170    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5171        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5172            return null;
5173        }
5174        synchronized (mPackages) {
5175            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5176                return null;
5177            }
5178            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5179            if (changedPackages == null) {
5180                return null;
5181            }
5182            final List<String> packageNames =
5183                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5184            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5185                final String packageName = changedPackages.get(i);
5186                if (packageName != null) {
5187                    packageNames.add(packageName);
5188                }
5189            }
5190            return packageNames.isEmpty()
5191                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5192        }
5193    }
5194
5195    @Override
5196    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5197        // allow instant applications
5198        ArrayList<FeatureInfo> res;
5199        synchronized (mAvailableFeatures) {
5200            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5201            res.addAll(mAvailableFeatures.values());
5202        }
5203        final FeatureInfo fi = new FeatureInfo();
5204        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5205                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5206        res.add(fi);
5207
5208        return new ParceledListSlice<>(res);
5209    }
5210
5211    @Override
5212    public boolean hasSystemFeature(String name, int version) {
5213        // allow instant applications
5214        synchronized (mAvailableFeatures) {
5215            final FeatureInfo feat = mAvailableFeatures.get(name);
5216            if (feat == null) {
5217                return false;
5218            } else {
5219                return feat.version >= version;
5220            }
5221        }
5222    }
5223
5224    @Override
5225    public int checkPermission(String permName, String pkgName, int userId) {
5226        if (!sUserManager.exists(userId)) {
5227            return PackageManager.PERMISSION_DENIED;
5228        }
5229        final int callingUid = Binder.getCallingUid();
5230
5231        synchronized (mPackages) {
5232            final PackageParser.Package p = mPackages.get(pkgName);
5233            if (p != null && p.mExtras != null) {
5234                final PackageSetting ps = (PackageSetting) p.mExtras;
5235                if (filterAppAccessLPr(ps, callingUid, userId)) {
5236                    return PackageManager.PERMISSION_DENIED;
5237                }
5238                final boolean instantApp = ps.getInstantApp(userId);
5239                final PermissionsState permissionsState = ps.getPermissionsState();
5240                if (permissionsState.hasPermission(permName, userId)) {
5241                    if (instantApp) {
5242                        BasePermission bp = mSettings.mPermissions.get(permName);
5243                        if (bp != null && bp.isInstant()) {
5244                            return PackageManager.PERMISSION_GRANTED;
5245                        }
5246                    } else {
5247                        return PackageManager.PERMISSION_GRANTED;
5248                    }
5249                }
5250                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5251                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5252                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5253                    return PackageManager.PERMISSION_GRANTED;
5254                }
5255            }
5256        }
5257
5258        return PackageManager.PERMISSION_DENIED;
5259    }
5260
5261    @Override
5262    public int checkUidPermission(String permName, int uid) {
5263        final int callingUid = Binder.getCallingUid();
5264        final int callingUserId = UserHandle.getUserId(callingUid);
5265        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5266        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5267        final int userId = UserHandle.getUserId(uid);
5268        if (!sUserManager.exists(userId)) {
5269            return PackageManager.PERMISSION_DENIED;
5270        }
5271
5272        synchronized (mPackages) {
5273            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5274            if (obj != null) {
5275                if (obj instanceof SharedUserSetting) {
5276                    if (isCallerInstantApp) {
5277                        return PackageManager.PERMISSION_DENIED;
5278                    }
5279                } else if (obj instanceof PackageSetting) {
5280                    final PackageSetting ps = (PackageSetting) obj;
5281                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5282                        return PackageManager.PERMISSION_DENIED;
5283                    }
5284                }
5285                final SettingBase settingBase = (SettingBase) obj;
5286                final PermissionsState permissionsState = settingBase.getPermissionsState();
5287                if (permissionsState.hasPermission(permName, userId)) {
5288                    if (isUidInstantApp) {
5289                        BasePermission bp = mSettings.mPermissions.get(permName);
5290                        if (bp != null && bp.isInstant()) {
5291                            return PackageManager.PERMISSION_GRANTED;
5292                        }
5293                    } else {
5294                        return PackageManager.PERMISSION_GRANTED;
5295                    }
5296                }
5297                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5298                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5299                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5300                    return PackageManager.PERMISSION_GRANTED;
5301                }
5302            } else {
5303                ArraySet<String> perms = mSystemPermissions.get(uid);
5304                if (perms != null) {
5305                    if (perms.contains(permName)) {
5306                        return PackageManager.PERMISSION_GRANTED;
5307                    }
5308                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5309                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5310                        return PackageManager.PERMISSION_GRANTED;
5311                    }
5312                }
5313            }
5314        }
5315
5316        return PackageManager.PERMISSION_DENIED;
5317    }
5318
5319    @Override
5320    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5321        if (UserHandle.getCallingUserId() != userId) {
5322            mContext.enforceCallingPermission(
5323                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5324                    "isPermissionRevokedByPolicy for user " + userId);
5325        }
5326
5327        if (checkPermission(permission, packageName, userId)
5328                == PackageManager.PERMISSION_GRANTED) {
5329            return false;
5330        }
5331
5332        final int callingUid = Binder.getCallingUid();
5333        if (getInstantAppPackageName(callingUid) != null) {
5334            if (!isCallerSameApp(packageName, callingUid)) {
5335                return false;
5336            }
5337        } else {
5338            if (isInstantApp(packageName, userId)) {
5339                return false;
5340            }
5341        }
5342
5343        final long identity = Binder.clearCallingIdentity();
5344        try {
5345            final int flags = getPermissionFlags(permission, packageName, userId);
5346            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5347        } finally {
5348            Binder.restoreCallingIdentity(identity);
5349        }
5350    }
5351
5352    @Override
5353    public String getPermissionControllerPackageName() {
5354        synchronized (mPackages) {
5355            return mRequiredInstallerPackage;
5356        }
5357    }
5358
5359    /**
5360     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5361     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5362     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5363     * @param message the message to log on security exception
5364     */
5365    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5366            boolean checkShell, String message) {
5367        if (userId < 0) {
5368            throw new IllegalArgumentException("Invalid userId " + userId);
5369        }
5370        if (checkShell) {
5371            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5372        }
5373        if (userId == UserHandle.getUserId(callingUid)) return;
5374        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5375            if (requireFullPermission) {
5376                mContext.enforceCallingOrSelfPermission(
5377                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5378            } else {
5379                try {
5380                    mContext.enforceCallingOrSelfPermission(
5381                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5382                } catch (SecurityException se) {
5383                    mContext.enforceCallingOrSelfPermission(
5384                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5385                }
5386            }
5387        }
5388    }
5389
5390    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5391        if (callingUid == Process.SHELL_UID) {
5392            if (userHandle >= 0
5393                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5394                throw new SecurityException("Shell does not have permission to access user "
5395                        + userHandle);
5396            } else if (userHandle < 0) {
5397                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5398                        + Debug.getCallers(3));
5399            }
5400        }
5401    }
5402
5403    private BasePermission findPermissionTreeLP(String permName) {
5404        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5405            if (permName.startsWith(bp.name) &&
5406                    permName.length() > bp.name.length() &&
5407                    permName.charAt(bp.name.length()) == '.') {
5408                return bp;
5409            }
5410        }
5411        return null;
5412    }
5413
5414    private BasePermission checkPermissionTreeLP(String permName) {
5415        if (permName != null) {
5416            BasePermission bp = findPermissionTreeLP(permName);
5417            if (bp != null) {
5418                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5419                    return bp;
5420                }
5421                throw new SecurityException("Calling uid "
5422                        + Binder.getCallingUid()
5423                        + " is not allowed to add to permission tree "
5424                        + bp.name + " owned by uid " + bp.uid);
5425            }
5426        }
5427        throw new SecurityException("No permission tree found for " + permName);
5428    }
5429
5430    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5431        if (s1 == null) {
5432            return s2 == null;
5433        }
5434        if (s2 == null) {
5435            return false;
5436        }
5437        if (s1.getClass() != s2.getClass()) {
5438            return false;
5439        }
5440        return s1.equals(s2);
5441    }
5442
5443    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5444        if (pi1.icon != pi2.icon) return false;
5445        if (pi1.logo != pi2.logo) return false;
5446        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5447        if (!compareStrings(pi1.name, pi2.name)) return false;
5448        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5449        // We'll take care of setting this one.
5450        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5451        // These are not currently stored in settings.
5452        //if (!compareStrings(pi1.group, pi2.group)) return false;
5453        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5454        //if (pi1.labelRes != pi2.labelRes) return false;
5455        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5456        return true;
5457    }
5458
5459    int permissionInfoFootprint(PermissionInfo info) {
5460        int size = info.name.length();
5461        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5462        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5463        return size;
5464    }
5465
5466    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5467        int size = 0;
5468        for (BasePermission perm : mSettings.mPermissions.values()) {
5469            if (perm.uid == tree.uid) {
5470                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5471            }
5472        }
5473        return size;
5474    }
5475
5476    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5477        // We calculate the max size of permissions defined by this uid and throw
5478        // if that plus the size of 'info' would exceed our stated maximum.
5479        if (tree.uid != Process.SYSTEM_UID) {
5480            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5481            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5482                throw new SecurityException("Permission tree size cap exceeded");
5483            }
5484        }
5485    }
5486
5487    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5488        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5489            throw new SecurityException("Instant apps can't add permissions");
5490        }
5491        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5492            throw new SecurityException("Label must be specified in permission");
5493        }
5494        BasePermission tree = checkPermissionTreeLP(info.name);
5495        BasePermission bp = mSettings.mPermissions.get(info.name);
5496        boolean added = bp == null;
5497        boolean changed = true;
5498        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5499        if (added) {
5500            enforcePermissionCapLocked(info, tree);
5501            bp = new BasePermission(info.name, tree.sourcePackage,
5502                    BasePermission.TYPE_DYNAMIC);
5503        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5504            throw new SecurityException(
5505                    "Not allowed to modify non-dynamic permission "
5506                    + info.name);
5507        } else {
5508            if (bp.protectionLevel == fixedLevel
5509                    && bp.perm.owner.equals(tree.perm.owner)
5510                    && bp.uid == tree.uid
5511                    && comparePermissionInfos(bp.perm.info, info)) {
5512                changed = false;
5513            }
5514        }
5515        bp.protectionLevel = fixedLevel;
5516        info = new PermissionInfo(info);
5517        info.protectionLevel = fixedLevel;
5518        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5519        bp.perm.info.packageName = tree.perm.info.packageName;
5520        bp.uid = tree.uid;
5521        if (added) {
5522            mSettings.mPermissions.put(info.name, bp);
5523        }
5524        if (changed) {
5525            if (!async) {
5526                mSettings.writeLPr();
5527            } else {
5528                scheduleWriteSettingsLocked();
5529            }
5530        }
5531        return added;
5532    }
5533
5534    @Override
5535    public boolean addPermission(PermissionInfo info) {
5536        synchronized (mPackages) {
5537            return addPermissionLocked(info, false);
5538        }
5539    }
5540
5541    @Override
5542    public boolean addPermissionAsync(PermissionInfo info) {
5543        synchronized (mPackages) {
5544            return addPermissionLocked(info, true);
5545        }
5546    }
5547
5548    @Override
5549    public void removePermission(String name) {
5550        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5551            throw new SecurityException("Instant applications don't have access to this method");
5552        }
5553        synchronized (mPackages) {
5554            checkPermissionTreeLP(name);
5555            BasePermission bp = mSettings.mPermissions.get(name);
5556            if (bp != null) {
5557                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5558                    throw new SecurityException(
5559                            "Not allowed to modify non-dynamic permission "
5560                            + name);
5561                }
5562                mSettings.mPermissions.remove(name);
5563                mSettings.writeLPr();
5564            }
5565        }
5566    }
5567
5568    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5569            PackageParser.Package pkg, BasePermission bp) {
5570        int index = pkg.requestedPermissions.indexOf(bp.name);
5571        if (index == -1) {
5572            throw new SecurityException("Package " + pkg.packageName
5573                    + " has not requested permission " + bp.name);
5574        }
5575        if (!bp.isRuntime() && !bp.isDevelopment()) {
5576            throw new SecurityException("Permission " + bp.name
5577                    + " is not a changeable permission type");
5578        }
5579    }
5580
5581    @Override
5582    public void grantRuntimePermission(String packageName, String name, final int userId) {
5583        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5584    }
5585
5586    private void grantRuntimePermission(String packageName, String name, final int userId,
5587            boolean overridePolicy) {
5588        if (!sUserManager.exists(userId)) {
5589            Log.e(TAG, "No such user:" + userId);
5590            return;
5591        }
5592        final int callingUid = Binder.getCallingUid();
5593
5594        mContext.enforceCallingOrSelfPermission(
5595                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5596                "grantRuntimePermission");
5597
5598        enforceCrossUserPermission(callingUid, userId,
5599                true /* requireFullPermission */, true /* checkShell */,
5600                "grantRuntimePermission");
5601
5602        final int uid;
5603        final PackageSetting ps;
5604
5605        synchronized (mPackages) {
5606            final PackageParser.Package pkg = mPackages.get(packageName);
5607            if (pkg == null) {
5608                throw new IllegalArgumentException("Unknown package: " + packageName);
5609            }
5610            final BasePermission bp = mSettings.mPermissions.get(name);
5611            if (bp == null) {
5612                throw new IllegalArgumentException("Unknown permission: " + name);
5613            }
5614            ps = (PackageSetting) pkg.mExtras;
5615            if (ps == null
5616                    || filterAppAccessLPr(ps, callingUid, userId)) {
5617                throw new IllegalArgumentException("Unknown package: " + packageName);
5618            }
5619
5620            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5621
5622            // If a permission review is required for legacy apps we represent
5623            // their permissions as always granted runtime ones since we need
5624            // to keep the review required permission flag per user while an
5625            // install permission's state is shared across all users.
5626            if (mPermissionReviewRequired
5627                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5628                    && bp.isRuntime()) {
5629                return;
5630            }
5631
5632            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5633
5634            final PermissionsState permissionsState = ps.getPermissionsState();
5635
5636            final int flags = permissionsState.getPermissionFlags(name, userId);
5637            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5638                throw new SecurityException("Cannot grant system fixed permission "
5639                        + name + " for package " + packageName);
5640            }
5641            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5642                throw new SecurityException("Cannot grant policy fixed permission "
5643                        + name + " for package " + packageName);
5644            }
5645
5646            if (bp.isDevelopment()) {
5647                // Development permissions must be handled specially, since they are not
5648                // normal runtime permissions.  For now they apply to all users.
5649                if (permissionsState.grantInstallPermission(bp) !=
5650                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5651                    scheduleWriteSettingsLocked();
5652                }
5653                return;
5654            }
5655
5656            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5657                throw new SecurityException("Cannot grant non-ephemeral permission"
5658                        + name + " for package " + packageName);
5659            }
5660
5661            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5662                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5663                return;
5664            }
5665
5666            final int result = permissionsState.grantRuntimePermission(bp, userId);
5667            switch (result) {
5668                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5669                    return;
5670                }
5671
5672                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5673                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5674                    mHandler.post(new Runnable() {
5675                        @Override
5676                        public void run() {
5677                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5678                        }
5679                    });
5680                }
5681                break;
5682            }
5683
5684            if (bp.isRuntime()) {
5685                logPermissionGranted(mContext, name, packageName);
5686            }
5687
5688            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5689
5690            // Not critical if that is lost - app has to request again.
5691            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5692        }
5693
5694        // Only need to do this if user is initialized. Otherwise it's a new user
5695        // and there are no processes running as the user yet and there's no need
5696        // to make an expensive call to remount processes for the changed permissions.
5697        if (READ_EXTERNAL_STORAGE.equals(name)
5698                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5699            final long token = Binder.clearCallingIdentity();
5700            try {
5701                if (sUserManager.isInitialized(userId)) {
5702                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5703                            StorageManagerInternal.class);
5704                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5705                }
5706            } finally {
5707                Binder.restoreCallingIdentity(token);
5708            }
5709        }
5710    }
5711
5712    @Override
5713    public void revokeRuntimePermission(String packageName, String name, int userId) {
5714        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5715    }
5716
5717    private void revokeRuntimePermission(String packageName, String name, int userId,
5718            boolean overridePolicy) {
5719        if (!sUserManager.exists(userId)) {
5720            Log.e(TAG, "No such user:" + userId);
5721            return;
5722        }
5723
5724        mContext.enforceCallingOrSelfPermission(
5725                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5726                "revokeRuntimePermission");
5727
5728        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5729                true /* requireFullPermission */, true /* checkShell */,
5730                "revokeRuntimePermission");
5731
5732        final int appId;
5733
5734        synchronized (mPackages) {
5735            final PackageParser.Package pkg = mPackages.get(packageName);
5736            if (pkg == null) {
5737                throw new IllegalArgumentException("Unknown package: " + packageName);
5738            }
5739            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5740            if (ps == null
5741                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5742                throw new IllegalArgumentException("Unknown package: " + packageName);
5743            }
5744            final BasePermission bp = mSettings.mPermissions.get(name);
5745            if (bp == null) {
5746                throw new IllegalArgumentException("Unknown permission: " + name);
5747            }
5748
5749            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5750
5751            // If a permission review is required for legacy apps we represent
5752            // their permissions as always granted runtime ones since we need
5753            // to keep the review required permission flag per user while an
5754            // install permission's state is shared across all users.
5755            if (mPermissionReviewRequired
5756                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5757                    && bp.isRuntime()) {
5758                return;
5759            }
5760
5761            final PermissionsState permissionsState = ps.getPermissionsState();
5762
5763            final int flags = permissionsState.getPermissionFlags(name, userId);
5764            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5765                throw new SecurityException("Cannot revoke system fixed permission "
5766                        + name + " for package " + packageName);
5767            }
5768            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5769                throw new SecurityException("Cannot revoke policy fixed permission "
5770                        + name + " for package " + packageName);
5771            }
5772
5773            if (bp.isDevelopment()) {
5774                // Development permissions must be handled specially, since they are not
5775                // normal runtime permissions.  For now they apply to all users.
5776                if (permissionsState.revokeInstallPermission(bp) !=
5777                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5778                    scheduleWriteSettingsLocked();
5779                }
5780                return;
5781            }
5782
5783            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5784                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5785                return;
5786            }
5787
5788            if (bp.isRuntime()) {
5789                logPermissionRevoked(mContext, name, packageName);
5790            }
5791
5792            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5793
5794            // Critical, after this call app should never have the permission.
5795            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5796
5797            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5798        }
5799
5800        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5801    }
5802
5803    /**
5804     * Get the first event id for the permission.
5805     *
5806     * <p>There are four events for each permission: <ul>
5807     *     <li>Request permission: first id + 0</li>
5808     *     <li>Grant permission: first id + 1</li>
5809     *     <li>Request for permission denied: first id + 2</li>
5810     *     <li>Revoke permission: first id + 3</li>
5811     * </ul></p>
5812     *
5813     * @param name name of the permission
5814     *
5815     * @return The first event id for the permission
5816     */
5817    private static int getBaseEventId(@NonNull String name) {
5818        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5819
5820        if (eventIdIndex == -1) {
5821            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5822                    || Build.IS_USER) {
5823                Log.i(TAG, "Unknown permission " + name);
5824
5825                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5826            } else {
5827                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5828                //
5829                // Also update
5830                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5831                // - metrics_constants.proto
5832                throw new IllegalStateException("Unknown permission " + name);
5833            }
5834        }
5835
5836        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5837    }
5838
5839    /**
5840     * Log that a permission was revoked.
5841     *
5842     * @param context Context of the caller
5843     * @param name name of the permission
5844     * @param packageName package permission if for
5845     */
5846    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5847            @NonNull String packageName) {
5848        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5849    }
5850
5851    /**
5852     * Log that a permission request was granted.
5853     *
5854     * @param context Context of the caller
5855     * @param name name of the permission
5856     * @param packageName package permission if for
5857     */
5858    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5859            @NonNull String packageName) {
5860        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5861    }
5862
5863    @Override
5864    public void resetRuntimePermissions() {
5865        mContext.enforceCallingOrSelfPermission(
5866                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5867                "revokeRuntimePermission");
5868
5869        int callingUid = Binder.getCallingUid();
5870        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5871            mContext.enforceCallingOrSelfPermission(
5872                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5873                    "resetRuntimePermissions");
5874        }
5875
5876        synchronized (mPackages) {
5877            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5878            for (int userId : UserManagerService.getInstance().getUserIds()) {
5879                final int packageCount = mPackages.size();
5880                for (int i = 0; i < packageCount; i++) {
5881                    PackageParser.Package pkg = mPackages.valueAt(i);
5882                    if (!(pkg.mExtras instanceof PackageSetting)) {
5883                        continue;
5884                    }
5885                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5886                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5887                }
5888            }
5889        }
5890    }
5891
5892    @Override
5893    public int getPermissionFlags(String name, String packageName, int userId) {
5894        if (!sUserManager.exists(userId)) {
5895            return 0;
5896        }
5897
5898        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5899
5900        final int callingUid = Binder.getCallingUid();
5901        enforceCrossUserPermission(callingUid, userId,
5902                true /* requireFullPermission */, false /* checkShell */,
5903                "getPermissionFlags");
5904
5905        synchronized (mPackages) {
5906            final PackageParser.Package pkg = mPackages.get(packageName);
5907            if (pkg == null) {
5908                return 0;
5909            }
5910            final BasePermission bp = mSettings.mPermissions.get(name);
5911            if (bp == null) {
5912                return 0;
5913            }
5914            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5915            if (ps == null
5916                    || filterAppAccessLPr(ps, callingUid, userId)) {
5917                return 0;
5918            }
5919            PermissionsState permissionsState = ps.getPermissionsState();
5920            return permissionsState.getPermissionFlags(name, userId);
5921        }
5922    }
5923
5924    @Override
5925    public void updatePermissionFlags(String name, String packageName, int flagMask,
5926            int flagValues, int userId) {
5927        if (!sUserManager.exists(userId)) {
5928            return;
5929        }
5930
5931        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5932
5933        final int callingUid = Binder.getCallingUid();
5934        enforceCrossUserPermission(callingUid, userId,
5935                true /* requireFullPermission */, true /* checkShell */,
5936                "updatePermissionFlags");
5937
5938        // Only the system can change these flags and nothing else.
5939        if (getCallingUid() != Process.SYSTEM_UID) {
5940            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5941            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5942            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5943            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5944            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5945        }
5946
5947        synchronized (mPackages) {
5948            final PackageParser.Package pkg = mPackages.get(packageName);
5949            if (pkg == null) {
5950                throw new IllegalArgumentException("Unknown package: " + packageName);
5951            }
5952            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5953            if (ps == null
5954                    || filterAppAccessLPr(ps, callingUid, userId)) {
5955                throw new IllegalArgumentException("Unknown package: " + packageName);
5956            }
5957
5958            final BasePermission bp = mSettings.mPermissions.get(name);
5959            if (bp == null) {
5960                throw new IllegalArgumentException("Unknown permission: " + name);
5961            }
5962
5963            PermissionsState permissionsState = ps.getPermissionsState();
5964
5965            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5966
5967            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5968                // Install and runtime permissions are stored in different places,
5969                // so figure out what permission changed and persist the change.
5970                if (permissionsState.getInstallPermissionState(name) != null) {
5971                    scheduleWriteSettingsLocked();
5972                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5973                        || hadState) {
5974                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5975                }
5976            }
5977        }
5978    }
5979
5980    /**
5981     * Update the permission flags for all packages and runtime permissions of a user in order
5982     * to allow device or profile owner to remove POLICY_FIXED.
5983     */
5984    @Override
5985    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5986        if (!sUserManager.exists(userId)) {
5987            return;
5988        }
5989
5990        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5991
5992        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5993                true /* requireFullPermission */, true /* checkShell */,
5994                "updatePermissionFlagsForAllApps");
5995
5996        // Only the system can change system fixed flags.
5997        if (getCallingUid() != Process.SYSTEM_UID) {
5998            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5999            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
6000        }
6001
6002        synchronized (mPackages) {
6003            boolean changed = false;
6004            final int packageCount = mPackages.size();
6005            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
6006                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
6007                final PackageSetting ps = (PackageSetting) pkg.mExtras;
6008                if (ps == null) {
6009                    continue;
6010                }
6011                PermissionsState permissionsState = ps.getPermissionsState();
6012                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
6013                        userId, flagMask, flagValues);
6014            }
6015            if (changed) {
6016                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6017            }
6018        }
6019    }
6020
6021    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
6022        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
6023                != PackageManager.PERMISSION_GRANTED
6024            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
6025                != PackageManager.PERMISSION_GRANTED) {
6026            throw new SecurityException(message + " requires "
6027                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
6028                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
6029        }
6030    }
6031
6032    @Override
6033    public boolean shouldShowRequestPermissionRationale(String permissionName,
6034            String packageName, int userId) {
6035        if (UserHandle.getCallingUserId() != userId) {
6036            mContext.enforceCallingPermission(
6037                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
6038                    "canShowRequestPermissionRationale for user " + userId);
6039        }
6040
6041        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
6042        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
6043            return false;
6044        }
6045
6046        if (checkPermission(permissionName, packageName, userId)
6047                == PackageManager.PERMISSION_GRANTED) {
6048            return false;
6049        }
6050
6051        final int flags;
6052
6053        final long identity = Binder.clearCallingIdentity();
6054        try {
6055            flags = getPermissionFlags(permissionName,
6056                    packageName, userId);
6057        } finally {
6058            Binder.restoreCallingIdentity(identity);
6059        }
6060
6061        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
6062                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
6063                | PackageManager.FLAG_PERMISSION_USER_FIXED;
6064
6065        if ((flags & fixedFlags) != 0) {
6066            return false;
6067        }
6068
6069        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
6070    }
6071
6072    @Override
6073    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6074        mContext.enforceCallingOrSelfPermission(
6075                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
6076                "addOnPermissionsChangeListener");
6077
6078        synchronized (mPackages) {
6079            mOnPermissionChangeListeners.addListenerLocked(listener);
6080        }
6081    }
6082
6083    @Override
6084    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6085        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6086            throw new SecurityException("Instant applications don't have access to this method");
6087        }
6088        synchronized (mPackages) {
6089            mOnPermissionChangeListeners.removeListenerLocked(listener);
6090        }
6091    }
6092
6093    @Override
6094    public boolean isProtectedBroadcast(String actionName) {
6095        // allow instant applications
6096        synchronized (mProtectedBroadcasts) {
6097            if (mProtectedBroadcasts.contains(actionName)) {
6098                return true;
6099            } else if (actionName != null) {
6100                // TODO: remove these terrible hacks
6101                if (actionName.startsWith("android.net.netmon.lingerExpired")
6102                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
6103                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
6104                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
6105                    return true;
6106                }
6107            }
6108        }
6109        return false;
6110    }
6111
6112    @Override
6113    public int checkSignatures(String pkg1, String pkg2) {
6114        synchronized (mPackages) {
6115            final PackageParser.Package p1 = mPackages.get(pkg1);
6116            final PackageParser.Package p2 = mPackages.get(pkg2);
6117            if (p1 == null || p1.mExtras == null
6118                    || p2 == null || p2.mExtras == null) {
6119                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6120            }
6121            final int callingUid = Binder.getCallingUid();
6122            final int callingUserId = UserHandle.getUserId(callingUid);
6123            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
6124            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
6125            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
6126                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
6127                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6128            }
6129            return compareSignatures(p1.mSignatures, p2.mSignatures);
6130        }
6131    }
6132
6133    @Override
6134    public int checkUidSignatures(int uid1, int uid2) {
6135        final int callingUid = Binder.getCallingUid();
6136        final int callingUserId = UserHandle.getUserId(callingUid);
6137        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6138        // Map to base uids.
6139        uid1 = UserHandle.getAppId(uid1);
6140        uid2 = UserHandle.getAppId(uid2);
6141        // reader
6142        synchronized (mPackages) {
6143            Signature[] s1;
6144            Signature[] s2;
6145            Object obj = mSettings.getUserIdLPr(uid1);
6146            if (obj != null) {
6147                if (obj instanceof SharedUserSetting) {
6148                    if (isCallerInstantApp) {
6149                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6150                    }
6151                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
6152                } else if (obj instanceof PackageSetting) {
6153                    final PackageSetting ps = (PackageSetting) obj;
6154                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6155                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6156                    }
6157                    s1 = ps.signatures.mSignatures;
6158                } else {
6159                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6160                }
6161            } else {
6162                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6163            }
6164            obj = mSettings.getUserIdLPr(uid2);
6165            if (obj != null) {
6166                if (obj instanceof SharedUserSetting) {
6167                    if (isCallerInstantApp) {
6168                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6169                    }
6170                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
6171                } else if (obj instanceof PackageSetting) {
6172                    final PackageSetting ps = (PackageSetting) obj;
6173                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6174                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6175                    }
6176                    s2 = ps.signatures.mSignatures;
6177                } else {
6178                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6179                }
6180            } else {
6181                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6182            }
6183            return compareSignatures(s1, s2);
6184        }
6185    }
6186
6187    /**
6188     * This method should typically only be used when granting or revoking
6189     * permissions, since the app may immediately restart after this call.
6190     * <p>
6191     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
6192     * guard your work against the app being relaunched.
6193     */
6194    private void killUid(int appId, int userId, String reason) {
6195        final long identity = Binder.clearCallingIdentity();
6196        try {
6197            IActivityManager am = ActivityManager.getService();
6198            if (am != null) {
6199                try {
6200                    am.killUid(appId, userId, reason);
6201                } catch (RemoteException e) {
6202                    /* ignore - same process */
6203                }
6204            }
6205        } finally {
6206            Binder.restoreCallingIdentity(identity);
6207        }
6208    }
6209
6210    /**
6211     * Compares two sets of signatures. Returns:
6212     * <br />
6213     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
6214     * <br />
6215     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
6216     * <br />
6217     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
6218     * <br />
6219     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
6220     * <br />
6221     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
6222     */
6223    static int compareSignatures(Signature[] s1, Signature[] s2) {
6224        if (s1 == null) {
6225            return s2 == null
6226                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
6227                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
6228        }
6229
6230        if (s2 == null) {
6231            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
6232        }
6233
6234        if (s1.length != s2.length) {
6235            return PackageManager.SIGNATURE_NO_MATCH;
6236        }
6237
6238        // Since both signature sets are of size 1, we can compare without HashSets.
6239        if (s1.length == 1) {
6240            return s1[0].equals(s2[0]) ?
6241                    PackageManager.SIGNATURE_MATCH :
6242                    PackageManager.SIGNATURE_NO_MATCH;
6243        }
6244
6245        ArraySet<Signature> set1 = new ArraySet<Signature>();
6246        for (Signature sig : s1) {
6247            set1.add(sig);
6248        }
6249        ArraySet<Signature> set2 = new ArraySet<Signature>();
6250        for (Signature sig : s2) {
6251            set2.add(sig);
6252        }
6253        // Make sure s2 contains all signatures in s1.
6254        if (set1.equals(set2)) {
6255            return PackageManager.SIGNATURE_MATCH;
6256        }
6257        return PackageManager.SIGNATURE_NO_MATCH;
6258    }
6259
6260    /**
6261     * If the database version for this type of package (internal storage or
6262     * external storage) is less than the version where package signatures
6263     * were updated, return true.
6264     */
6265    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6266        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6267        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6268    }
6269
6270    /**
6271     * Used for backward compatibility to make sure any packages with
6272     * certificate chains get upgraded to the new style. {@code existingSigs}
6273     * will be in the old format (since they were stored on disk from before the
6274     * system upgrade) and {@code scannedSigs} will be in the newer format.
6275     */
6276    private int compareSignaturesCompat(PackageSignatures existingSigs,
6277            PackageParser.Package scannedPkg) {
6278        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6279            return PackageManager.SIGNATURE_NO_MATCH;
6280        }
6281
6282        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6283        for (Signature sig : existingSigs.mSignatures) {
6284            existingSet.add(sig);
6285        }
6286        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6287        for (Signature sig : scannedPkg.mSignatures) {
6288            try {
6289                Signature[] chainSignatures = sig.getChainSignatures();
6290                for (Signature chainSig : chainSignatures) {
6291                    scannedCompatSet.add(chainSig);
6292                }
6293            } catch (CertificateEncodingException e) {
6294                scannedCompatSet.add(sig);
6295            }
6296        }
6297        /*
6298         * Make sure the expanded scanned set contains all signatures in the
6299         * existing one.
6300         */
6301        if (scannedCompatSet.equals(existingSet)) {
6302            // Migrate the old signatures to the new scheme.
6303            existingSigs.assignSignatures(scannedPkg.mSignatures);
6304            // The new KeySets will be re-added later in the scanning process.
6305            synchronized (mPackages) {
6306                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6307            }
6308            return PackageManager.SIGNATURE_MATCH;
6309        }
6310        return PackageManager.SIGNATURE_NO_MATCH;
6311    }
6312
6313    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6314        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6315        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6316    }
6317
6318    private int compareSignaturesRecover(PackageSignatures existingSigs,
6319            PackageParser.Package scannedPkg) {
6320        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6321            return PackageManager.SIGNATURE_NO_MATCH;
6322        }
6323
6324        String msg = null;
6325        try {
6326            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6327                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6328                        + scannedPkg.packageName);
6329                return PackageManager.SIGNATURE_MATCH;
6330            }
6331        } catch (CertificateException e) {
6332            msg = e.getMessage();
6333        }
6334
6335        logCriticalInfo(Log.INFO,
6336                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6337        return PackageManager.SIGNATURE_NO_MATCH;
6338    }
6339
6340    @Override
6341    public List<String> getAllPackages() {
6342        final int callingUid = Binder.getCallingUid();
6343        final int callingUserId = UserHandle.getUserId(callingUid);
6344        synchronized (mPackages) {
6345            if (canViewInstantApps(callingUid, callingUserId)) {
6346                return new ArrayList<String>(mPackages.keySet());
6347            }
6348            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6349            final List<String> result = new ArrayList<>();
6350            if (instantAppPkgName != null) {
6351                // caller is an instant application; filter unexposed applications
6352                for (PackageParser.Package pkg : mPackages.values()) {
6353                    if (!pkg.visibleToInstantApps) {
6354                        continue;
6355                    }
6356                    result.add(pkg.packageName);
6357                }
6358            } else {
6359                // caller is a normal application; filter instant applications
6360                for (PackageParser.Package pkg : mPackages.values()) {
6361                    final PackageSetting ps =
6362                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6363                    if (ps != null
6364                            && ps.getInstantApp(callingUserId)
6365                            && !mInstantAppRegistry.isInstantAccessGranted(
6366                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6367                        continue;
6368                    }
6369                    result.add(pkg.packageName);
6370                }
6371            }
6372            return result;
6373        }
6374    }
6375
6376    @Override
6377    public String[] getPackagesForUid(int uid) {
6378        final int callingUid = Binder.getCallingUid();
6379        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6380        final int userId = UserHandle.getUserId(uid);
6381        uid = UserHandle.getAppId(uid);
6382        // reader
6383        synchronized (mPackages) {
6384            Object obj = mSettings.getUserIdLPr(uid);
6385            if (obj instanceof SharedUserSetting) {
6386                if (isCallerInstantApp) {
6387                    return null;
6388                }
6389                final SharedUserSetting sus = (SharedUserSetting) obj;
6390                final int N = sus.packages.size();
6391                String[] res = new String[N];
6392                final Iterator<PackageSetting> it = sus.packages.iterator();
6393                int i = 0;
6394                while (it.hasNext()) {
6395                    PackageSetting ps = it.next();
6396                    if (ps.getInstalled(userId)) {
6397                        res[i++] = ps.name;
6398                    } else {
6399                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6400                    }
6401                }
6402                return res;
6403            } else if (obj instanceof PackageSetting) {
6404                final PackageSetting ps = (PackageSetting) obj;
6405                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6406                    return new String[]{ps.name};
6407                }
6408            }
6409        }
6410        return null;
6411    }
6412
6413    @Override
6414    public String getNameForUid(int uid) {
6415        final int callingUid = Binder.getCallingUid();
6416        if (getInstantAppPackageName(callingUid) != null) {
6417            return null;
6418        }
6419        synchronized (mPackages) {
6420            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6421            if (obj instanceof SharedUserSetting) {
6422                final SharedUserSetting sus = (SharedUserSetting) obj;
6423                return sus.name + ":" + sus.userId;
6424            } else if (obj instanceof PackageSetting) {
6425                final PackageSetting ps = (PackageSetting) obj;
6426                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6427                    return null;
6428                }
6429                return ps.name;
6430            }
6431            return null;
6432        }
6433    }
6434
6435    @Override
6436    public String[] getNamesForUids(int[] uids) {
6437        if (uids == null || uids.length == 0) {
6438            return null;
6439        }
6440        final int callingUid = Binder.getCallingUid();
6441        if (getInstantAppPackageName(callingUid) != null) {
6442            return null;
6443        }
6444        final String[] names = new String[uids.length];
6445        synchronized (mPackages) {
6446            for (int i = uids.length - 1; i >= 0; i--) {
6447                final int uid = uids[i];
6448                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6449                if (obj instanceof SharedUserSetting) {
6450                    final SharedUserSetting sus = (SharedUserSetting) obj;
6451                    names[i] = "shared:" + sus.name;
6452                } else if (obj instanceof PackageSetting) {
6453                    final PackageSetting ps = (PackageSetting) obj;
6454                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6455                        names[i] = null;
6456                    } else {
6457                        names[i] = ps.name;
6458                    }
6459                } else {
6460                    names[i] = null;
6461                }
6462            }
6463        }
6464        return names;
6465    }
6466
6467    @Override
6468    public int getUidForSharedUser(String sharedUserName) {
6469        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6470            return -1;
6471        }
6472        if (sharedUserName == null) {
6473            return -1;
6474        }
6475        // reader
6476        synchronized (mPackages) {
6477            SharedUserSetting suid;
6478            try {
6479                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6480                if (suid != null) {
6481                    return suid.userId;
6482                }
6483            } catch (PackageManagerException ignore) {
6484                // can't happen, but, still need to catch it
6485            }
6486            return -1;
6487        }
6488    }
6489
6490    @Override
6491    public int getFlagsForUid(int uid) {
6492        final int callingUid = Binder.getCallingUid();
6493        if (getInstantAppPackageName(callingUid) != null) {
6494            return 0;
6495        }
6496        synchronized (mPackages) {
6497            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6498            if (obj instanceof SharedUserSetting) {
6499                final SharedUserSetting sus = (SharedUserSetting) obj;
6500                return sus.pkgFlags;
6501            } else if (obj instanceof PackageSetting) {
6502                final PackageSetting ps = (PackageSetting) obj;
6503                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6504                    return 0;
6505                }
6506                return ps.pkgFlags;
6507            }
6508        }
6509        return 0;
6510    }
6511
6512    @Override
6513    public int getPrivateFlagsForUid(int uid) {
6514        final int callingUid = Binder.getCallingUid();
6515        if (getInstantAppPackageName(callingUid) != null) {
6516            return 0;
6517        }
6518        synchronized (mPackages) {
6519            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6520            if (obj instanceof SharedUserSetting) {
6521                final SharedUserSetting sus = (SharedUserSetting) obj;
6522                return sus.pkgPrivateFlags;
6523            } else if (obj instanceof PackageSetting) {
6524                final PackageSetting ps = (PackageSetting) obj;
6525                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6526                    return 0;
6527                }
6528                return ps.pkgPrivateFlags;
6529            }
6530        }
6531        return 0;
6532    }
6533
6534    @Override
6535    public boolean isUidPrivileged(int uid) {
6536        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6537            return false;
6538        }
6539        uid = UserHandle.getAppId(uid);
6540        // reader
6541        synchronized (mPackages) {
6542            Object obj = mSettings.getUserIdLPr(uid);
6543            if (obj instanceof SharedUserSetting) {
6544                final SharedUserSetting sus = (SharedUserSetting) obj;
6545                final Iterator<PackageSetting> it = sus.packages.iterator();
6546                while (it.hasNext()) {
6547                    if (it.next().isPrivileged()) {
6548                        return true;
6549                    }
6550                }
6551            } else if (obj instanceof PackageSetting) {
6552                final PackageSetting ps = (PackageSetting) obj;
6553                return ps.isPrivileged();
6554            }
6555        }
6556        return false;
6557    }
6558
6559    @Override
6560    public String[] getAppOpPermissionPackages(String permissionName) {
6561        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6562            return null;
6563        }
6564        synchronized (mPackages) {
6565            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6566            if (pkgs == null) {
6567                return null;
6568            }
6569            return pkgs.toArray(new String[pkgs.size()]);
6570        }
6571    }
6572
6573    @Override
6574    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6575            int flags, int userId) {
6576        return resolveIntentInternal(
6577                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6578    }
6579
6580    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6581            int flags, int userId, boolean resolveForStart) {
6582        try {
6583            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6584
6585            if (!sUserManager.exists(userId)) return null;
6586            final int callingUid = Binder.getCallingUid();
6587            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6588            enforceCrossUserPermission(callingUid, userId,
6589                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6590
6591            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6592            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6593                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
6594            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6595
6596            final ResolveInfo bestChoice =
6597                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6598            return bestChoice;
6599        } finally {
6600            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6601        }
6602    }
6603
6604    @Override
6605    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6606        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6607            throw new SecurityException(
6608                    "findPersistentPreferredActivity can only be run by the system");
6609        }
6610        if (!sUserManager.exists(userId)) {
6611            return null;
6612        }
6613        final int callingUid = Binder.getCallingUid();
6614        intent = updateIntentForResolve(intent);
6615        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6616        final int flags = updateFlagsForResolve(
6617                0, userId, intent, callingUid, false /*includeInstantApps*/);
6618        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6619                userId);
6620        synchronized (mPackages) {
6621            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6622                    userId);
6623        }
6624    }
6625
6626    @Override
6627    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6628            IntentFilter filter, int match, ComponentName activity) {
6629        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6630            return;
6631        }
6632        final int userId = UserHandle.getCallingUserId();
6633        if (DEBUG_PREFERRED) {
6634            Log.v(TAG, "setLastChosenActivity intent=" + intent
6635                + " resolvedType=" + resolvedType
6636                + " flags=" + flags
6637                + " filter=" + filter
6638                + " match=" + match
6639                + " activity=" + activity);
6640            filter.dump(new PrintStreamPrinter(System.out), "    ");
6641        }
6642        intent.setComponent(null);
6643        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6644                userId);
6645        // Find any earlier preferred or last chosen entries and nuke them
6646        findPreferredActivity(intent, resolvedType,
6647                flags, query, 0, false, true, false, userId);
6648        // Add the new activity as the last chosen for this filter
6649        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6650                "Setting last chosen");
6651    }
6652
6653    @Override
6654    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6655        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6656            return null;
6657        }
6658        final int userId = UserHandle.getCallingUserId();
6659        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6660        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6661                userId);
6662        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6663                false, false, false, userId);
6664    }
6665
6666    /**
6667     * Returns whether or not instant apps have been disabled remotely.
6668     */
6669    private boolean isEphemeralDisabled() {
6670        return mEphemeralAppsDisabled;
6671    }
6672
6673    private boolean isInstantAppAllowed(
6674            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6675            boolean skipPackageCheck) {
6676        if (mInstantAppResolverConnection == null) {
6677            return false;
6678        }
6679        if (mInstantAppInstallerActivity == null) {
6680            return false;
6681        }
6682        if (intent.getComponent() != null) {
6683            return false;
6684        }
6685        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6686            return false;
6687        }
6688        if (!skipPackageCheck && intent.getPackage() != null) {
6689            return false;
6690        }
6691        final boolean isWebUri = hasWebURI(intent);
6692        if (!isWebUri || intent.getData().getHost() == null) {
6693            return false;
6694        }
6695        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6696        // Or if there's already an ephemeral app installed that handles the action
6697        synchronized (mPackages) {
6698            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6699            for (int n = 0; n < count; n++) {
6700                final ResolveInfo info = resolvedActivities.get(n);
6701                final String packageName = info.activityInfo.packageName;
6702                final PackageSetting ps = mSettings.mPackages.get(packageName);
6703                if (ps != null) {
6704                    // only check domain verification status if the app is not a browser
6705                    if (!info.handleAllWebDataURI) {
6706                        // Try to get the status from User settings first
6707                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6708                        final int status = (int) (packedStatus >> 32);
6709                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6710                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6711                            if (DEBUG_EPHEMERAL) {
6712                                Slog.v(TAG, "DENY instant app;"
6713                                    + " pkg: " + packageName + ", status: " + status);
6714                            }
6715                            return false;
6716                        }
6717                    }
6718                    if (ps.getInstantApp(userId)) {
6719                        if (DEBUG_EPHEMERAL) {
6720                            Slog.v(TAG, "DENY instant app installed;"
6721                                    + " pkg: " + packageName);
6722                        }
6723                        return false;
6724                    }
6725                }
6726            }
6727        }
6728        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6729        return true;
6730    }
6731
6732    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6733            Intent origIntent, String resolvedType, String callingPackage,
6734            Bundle verificationBundle, int userId) {
6735        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6736                new InstantAppRequest(responseObj, origIntent, resolvedType,
6737                        callingPackage, userId, verificationBundle));
6738        mHandler.sendMessage(msg);
6739    }
6740
6741    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6742            int flags, List<ResolveInfo> query, int userId) {
6743        if (query != null) {
6744            final int N = query.size();
6745            if (N == 1) {
6746                return query.get(0);
6747            } else if (N > 1) {
6748                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6749                // If there is more than one activity with the same priority,
6750                // then let the user decide between them.
6751                ResolveInfo r0 = query.get(0);
6752                ResolveInfo r1 = query.get(1);
6753                if (DEBUG_INTENT_MATCHING || debug) {
6754                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6755                            + r1.activityInfo.name + "=" + r1.priority);
6756                }
6757                // If the first activity has a higher priority, or a different
6758                // default, then it is always desirable to pick it.
6759                if (r0.priority != r1.priority
6760                        || r0.preferredOrder != r1.preferredOrder
6761                        || r0.isDefault != r1.isDefault) {
6762                    return query.get(0);
6763                }
6764                // If we have saved a preference for a preferred activity for
6765                // this Intent, use that.
6766                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6767                        flags, query, r0.priority, true, false, debug, userId);
6768                if (ri != null) {
6769                    return ri;
6770                }
6771                // If we have an ephemeral app, use it
6772                for (int i = 0; i < N; i++) {
6773                    ri = query.get(i);
6774                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6775                        final String packageName = ri.activityInfo.packageName;
6776                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6777                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6778                        final int status = (int)(packedStatus >> 32);
6779                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6780                            return ri;
6781                        }
6782                    }
6783                }
6784                ri = new ResolveInfo(mResolveInfo);
6785                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6786                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6787                // If all of the options come from the same package, show the application's
6788                // label and icon instead of the generic resolver's.
6789                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6790                // and then throw away the ResolveInfo itself, meaning that the caller loses
6791                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6792                // a fallback for this case; we only set the target package's resources on
6793                // the ResolveInfo, not the ActivityInfo.
6794                final String intentPackage = intent.getPackage();
6795                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6796                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6797                    ri.resolvePackageName = intentPackage;
6798                    if (userNeedsBadging(userId)) {
6799                        ri.noResourceId = true;
6800                    } else {
6801                        ri.icon = appi.icon;
6802                    }
6803                    ri.iconResourceId = appi.icon;
6804                    ri.labelRes = appi.labelRes;
6805                }
6806                ri.activityInfo.applicationInfo = new ApplicationInfo(
6807                        ri.activityInfo.applicationInfo);
6808                if (userId != 0) {
6809                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6810                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6811                }
6812                // Make sure that the resolver is displayable in car mode
6813                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6814                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6815                return ri;
6816            }
6817        }
6818        return null;
6819    }
6820
6821    /**
6822     * Return true if the given list is not empty and all of its contents have
6823     * an activityInfo with the given package name.
6824     */
6825    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6826        if (ArrayUtils.isEmpty(list)) {
6827            return false;
6828        }
6829        for (int i = 0, N = list.size(); i < N; i++) {
6830            final ResolveInfo ri = list.get(i);
6831            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6832            if (ai == null || !packageName.equals(ai.packageName)) {
6833                return false;
6834            }
6835        }
6836        return true;
6837    }
6838
6839    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6840            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6841        final int N = query.size();
6842        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6843                .get(userId);
6844        // Get the list of persistent preferred activities that handle the intent
6845        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6846        List<PersistentPreferredActivity> pprefs = ppir != null
6847                ? ppir.queryIntent(intent, resolvedType,
6848                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6849                        userId)
6850                : null;
6851        if (pprefs != null && pprefs.size() > 0) {
6852            final int M = pprefs.size();
6853            for (int i=0; i<M; i++) {
6854                final PersistentPreferredActivity ppa = pprefs.get(i);
6855                if (DEBUG_PREFERRED || debug) {
6856                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6857                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6858                            + "\n  component=" + ppa.mComponent);
6859                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6860                }
6861                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6862                        flags | MATCH_DISABLED_COMPONENTS, userId);
6863                if (DEBUG_PREFERRED || debug) {
6864                    Slog.v(TAG, "Found persistent preferred activity:");
6865                    if (ai != null) {
6866                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6867                    } else {
6868                        Slog.v(TAG, "  null");
6869                    }
6870                }
6871                if (ai == null) {
6872                    // This previously registered persistent preferred activity
6873                    // component is no longer known. Ignore it and do NOT remove it.
6874                    continue;
6875                }
6876                for (int j=0; j<N; j++) {
6877                    final ResolveInfo ri = query.get(j);
6878                    if (!ri.activityInfo.applicationInfo.packageName
6879                            .equals(ai.applicationInfo.packageName)) {
6880                        continue;
6881                    }
6882                    if (!ri.activityInfo.name.equals(ai.name)) {
6883                        continue;
6884                    }
6885                    //  Found a persistent preference that can handle the intent.
6886                    if (DEBUG_PREFERRED || debug) {
6887                        Slog.v(TAG, "Returning persistent preferred activity: " +
6888                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6889                    }
6890                    return ri;
6891                }
6892            }
6893        }
6894        return null;
6895    }
6896
6897    // TODO: handle preferred activities missing while user has amnesia
6898    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6899            List<ResolveInfo> query, int priority, boolean always,
6900            boolean removeMatches, boolean debug, int userId) {
6901        if (!sUserManager.exists(userId)) return null;
6902        final int callingUid = Binder.getCallingUid();
6903        flags = updateFlagsForResolve(
6904                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6905        intent = updateIntentForResolve(intent);
6906        // writer
6907        synchronized (mPackages) {
6908            // Try to find a matching persistent preferred activity.
6909            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6910                    debug, userId);
6911
6912            // If a persistent preferred activity matched, use it.
6913            if (pri != null) {
6914                return pri;
6915            }
6916
6917            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6918            // Get the list of preferred activities that handle the intent
6919            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6920            List<PreferredActivity> prefs = pir != null
6921                    ? pir.queryIntent(intent, resolvedType,
6922                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6923                            userId)
6924                    : null;
6925            if (prefs != null && prefs.size() > 0) {
6926                boolean changed = false;
6927                try {
6928                    // First figure out how good the original match set is.
6929                    // We will only allow preferred activities that came
6930                    // from the same match quality.
6931                    int match = 0;
6932
6933                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6934
6935                    final int N = query.size();
6936                    for (int j=0; j<N; j++) {
6937                        final ResolveInfo ri = query.get(j);
6938                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6939                                + ": 0x" + Integer.toHexString(match));
6940                        if (ri.match > match) {
6941                            match = ri.match;
6942                        }
6943                    }
6944
6945                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6946                            + Integer.toHexString(match));
6947
6948                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6949                    final int M = prefs.size();
6950                    for (int i=0; i<M; i++) {
6951                        final PreferredActivity pa = prefs.get(i);
6952                        if (DEBUG_PREFERRED || debug) {
6953                            Slog.v(TAG, "Checking PreferredActivity ds="
6954                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6955                                    + "\n  component=" + pa.mPref.mComponent);
6956                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6957                        }
6958                        if (pa.mPref.mMatch != match) {
6959                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6960                                    + Integer.toHexString(pa.mPref.mMatch));
6961                            continue;
6962                        }
6963                        // If it's not an "always" type preferred activity and that's what we're
6964                        // looking for, skip it.
6965                        if (always && !pa.mPref.mAlways) {
6966                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6967                            continue;
6968                        }
6969                        final ActivityInfo ai = getActivityInfo(
6970                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6971                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6972                                userId);
6973                        if (DEBUG_PREFERRED || debug) {
6974                            Slog.v(TAG, "Found preferred activity:");
6975                            if (ai != null) {
6976                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6977                            } else {
6978                                Slog.v(TAG, "  null");
6979                            }
6980                        }
6981                        if (ai == null) {
6982                            // This previously registered preferred activity
6983                            // component is no longer known.  Most likely an update
6984                            // to the app was installed and in the new version this
6985                            // component no longer exists.  Clean it up by removing
6986                            // it from the preferred activities list, and skip it.
6987                            Slog.w(TAG, "Removing dangling preferred activity: "
6988                                    + pa.mPref.mComponent);
6989                            pir.removeFilter(pa);
6990                            changed = true;
6991                            continue;
6992                        }
6993                        for (int j=0; j<N; j++) {
6994                            final ResolveInfo ri = query.get(j);
6995                            if (!ri.activityInfo.applicationInfo.packageName
6996                                    .equals(ai.applicationInfo.packageName)) {
6997                                continue;
6998                            }
6999                            if (!ri.activityInfo.name.equals(ai.name)) {
7000                                continue;
7001                            }
7002
7003                            if (removeMatches) {
7004                                pir.removeFilter(pa);
7005                                changed = true;
7006                                if (DEBUG_PREFERRED) {
7007                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
7008                                }
7009                                break;
7010                            }
7011
7012                            // Okay we found a previously set preferred or last chosen app.
7013                            // If the result set is different from when this
7014                            // was created, we need to clear it and re-ask the
7015                            // user their preference, if we're looking for an "always" type entry.
7016                            if (always && !pa.mPref.sameSet(query)) {
7017                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
7018                                        + intent + " type " + resolvedType);
7019                                if (DEBUG_PREFERRED) {
7020                                    Slog.v(TAG, "Removing preferred activity since set changed "
7021                                            + pa.mPref.mComponent);
7022                                }
7023                                pir.removeFilter(pa);
7024                                // Re-add the filter as a "last chosen" entry (!always)
7025                                PreferredActivity lastChosen = new PreferredActivity(
7026                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
7027                                pir.addFilter(lastChosen);
7028                                changed = true;
7029                                return null;
7030                            }
7031
7032                            // Yay! Either the set matched or we're looking for the last chosen
7033                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
7034                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
7035                            return ri;
7036                        }
7037                    }
7038                } finally {
7039                    if (changed) {
7040                        if (DEBUG_PREFERRED) {
7041                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
7042                        }
7043                        scheduleWritePackageRestrictionsLocked(userId);
7044                    }
7045                }
7046            }
7047        }
7048        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
7049        return null;
7050    }
7051
7052    /*
7053     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
7054     */
7055    @Override
7056    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
7057            int targetUserId) {
7058        mContext.enforceCallingOrSelfPermission(
7059                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
7060        List<CrossProfileIntentFilter> matches =
7061                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
7062        if (matches != null) {
7063            int size = matches.size();
7064            for (int i = 0; i < size; i++) {
7065                if (matches.get(i).getTargetUserId() == targetUserId) return true;
7066            }
7067        }
7068        if (hasWebURI(intent)) {
7069            // cross-profile app linking works only towards the parent.
7070            final int callingUid = Binder.getCallingUid();
7071            final UserInfo parent = getProfileParent(sourceUserId);
7072            synchronized(mPackages) {
7073                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
7074                        false /*includeInstantApps*/);
7075                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
7076                        intent, resolvedType, flags, sourceUserId, parent.id);
7077                return xpDomainInfo != null;
7078            }
7079        }
7080        return false;
7081    }
7082
7083    private UserInfo getProfileParent(int userId) {
7084        final long identity = Binder.clearCallingIdentity();
7085        try {
7086            return sUserManager.getProfileParent(userId);
7087        } finally {
7088            Binder.restoreCallingIdentity(identity);
7089        }
7090    }
7091
7092    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
7093            String resolvedType, int userId) {
7094        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
7095        if (resolver != null) {
7096            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
7097        }
7098        return null;
7099    }
7100
7101    @Override
7102    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
7103            String resolvedType, int flags, int userId) {
7104        try {
7105            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
7106
7107            return new ParceledListSlice<>(
7108                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
7109        } finally {
7110            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7111        }
7112    }
7113
7114    /**
7115     * Returns the package name of the calling Uid if it's an instant app. If it isn't
7116     * instant, returns {@code null}.
7117     */
7118    private String getInstantAppPackageName(int callingUid) {
7119        synchronized (mPackages) {
7120            // If the caller is an isolated app use the owner's uid for the lookup.
7121            if (Process.isIsolated(callingUid)) {
7122                callingUid = mIsolatedOwners.get(callingUid);
7123            }
7124            final int appId = UserHandle.getAppId(callingUid);
7125            final Object obj = mSettings.getUserIdLPr(appId);
7126            if (obj instanceof PackageSetting) {
7127                final PackageSetting ps = (PackageSetting) obj;
7128                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
7129                return isInstantApp ? ps.pkg.packageName : null;
7130            }
7131        }
7132        return null;
7133    }
7134
7135    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7136            String resolvedType, int flags, int userId) {
7137        return queryIntentActivitiesInternal(
7138                intent, resolvedType, flags, Binder.getCallingUid(), userId,
7139                false /*resolveForStart*/, true /*allowDynamicSplits*/);
7140    }
7141
7142    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7143            String resolvedType, int flags, int filterCallingUid, int userId,
7144            boolean resolveForStart, boolean allowDynamicSplits) {
7145        if (!sUserManager.exists(userId)) return Collections.emptyList();
7146        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
7147        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7148                false /* requireFullPermission */, false /* checkShell */,
7149                "query intent activities");
7150        final String pkgName = intent.getPackage();
7151        ComponentName comp = intent.getComponent();
7152        if (comp == null) {
7153            if (intent.getSelector() != null) {
7154                intent = intent.getSelector();
7155                comp = intent.getComponent();
7156            }
7157        }
7158
7159        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
7160                comp != null || pkgName != null /*onlyExposedExplicitly*/);
7161        if (comp != null) {
7162            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7163            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
7164            if (ai != null) {
7165                // When specifying an explicit component, we prevent the activity from being
7166                // used when either 1) the calling package is normal and the activity is within
7167                // an ephemeral application or 2) the calling package is ephemeral and the
7168                // activity is not visible to ephemeral applications.
7169                final boolean matchInstantApp =
7170                        (flags & PackageManager.MATCH_INSTANT) != 0;
7171                final boolean matchVisibleToInstantAppOnly =
7172                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7173                final boolean matchExplicitlyVisibleOnly =
7174                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7175                final boolean isCallerInstantApp =
7176                        instantAppPkgName != null;
7177                final boolean isTargetSameInstantApp =
7178                        comp.getPackageName().equals(instantAppPkgName);
7179                final boolean isTargetInstantApp =
7180                        (ai.applicationInfo.privateFlags
7181                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7182                final boolean isTargetVisibleToInstantApp =
7183                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7184                final boolean isTargetExplicitlyVisibleToInstantApp =
7185                        isTargetVisibleToInstantApp
7186                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7187                final boolean isTargetHiddenFromInstantApp =
7188                        !isTargetVisibleToInstantApp
7189                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7190                final boolean blockResolution =
7191                        !isTargetSameInstantApp
7192                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7193                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7194                                        && isTargetHiddenFromInstantApp));
7195                if (!blockResolution) {
7196                    final ResolveInfo ri = new ResolveInfo();
7197                    ri.activityInfo = ai;
7198                    list.add(ri);
7199                }
7200            }
7201            return applyPostResolutionFilter(
7202                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7203        }
7204
7205        // reader
7206        boolean sortResult = false;
7207        boolean addEphemeral = false;
7208        List<ResolveInfo> result;
7209        final boolean ephemeralDisabled = isEphemeralDisabled();
7210        synchronized (mPackages) {
7211            if (pkgName == null) {
7212                List<CrossProfileIntentFilter> matchingFilters =
7213                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
7214                // Check for results that need to skip the current profile.
7215                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
7216                        resolvedType, flags, userId);
7217                if (xpResolveInfo != null) {
7218                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
7219                    xpResult.add(xpResolveInfo);
7220                    return applyPostResolutionFilter(
7221                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
7222                            allowDynamicSplits, filterCallingUid, userId);
7223                }
7224
7225                // Check for results in the current profile.
7226                result = filterIfNotSystemUser(mActivities.queryIntent(
7227                        intent, resolvedType, flags, userId), userId);
7228                addEphemeral = !ephemeralDisabled
7229                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
7230                // Check for cross profile results.
7231                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
7232                xpResolveInfo = queryCrossProfileIntents(
7233                        matchingFilters, intent, resolvedType, flags, userId,
7234                        hasNonNegativePriorityResult);
7235                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
7236                    boolean isVisibleToUser = filterIfNotSystemUser(
7237                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
7238                    if (isVisibleToUser) {
7239                        result.add(xpResolveInfo);
7240                        sortResult = true;
7241                    }
7242                }
7243                if (hasWebURI(intent)) {
7244                    CrossProfileDomainInfo xpDomainInfo = null;
7245                    final UserInfo parent = getProfileParent(userId);
7246                    if (parent != null) {
7247                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
7248                                flags, userId, parent.id);
7249                    }
7250                    if (xpDomainInfo != null) {
7251                        if (xpResolveInfo != null) {
7252                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
7253                            // in the result.
7254                            result.remove(xpResolveInfo);
7255                        }
7256                        if (result.size() == 0 && !addEphemeral) {
7257                            // No result in current profile, but found candidate in parent user.
7258                            // And we are not going to add emphemeral app, so we can return the
7259                            // result straight away.
7260                            result.add(xpDomainInfo.resolveInfo);
7261                            return applyPostResolutionFilter(result, instantAppPkgName,
7262                                    allowDynamicSplits, filterCallingUid, userId);
7263                        }
7264                    } else if (result.size() <= 1 && !addEphemeral) {
7265                        // No result in parent user and <= 1 result in current profile, and we
7266                        // are not going to add emphemeral app, so we can return the result without
7267                        // further processing.
7268                        return applyPostResolutionFilter(result, instantAppPkgName,
7269                                allowDynamicSplits, filterCallingUid, userId);
7270                    }
7271                    // We have more than one candidate (combining results from current and parent
7272                    // profile), so we need filtering and sorting.
7273                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
7274                            intent, flags, result, xpDomainInfo, userId);
7275                    sortResult = true;
7276                }
7277            } else {
7278                final PackageParser.Package pkg = mPackages.get(pkgName);
7279                result = null;
7280                if (pkg != null) {
7281                    result = filterIfNotSystemUser(
7282                            mActivities.queryIntentForPackage(
7283                                    intent, resolvedType, flags, pkg.activities, userId),
7284                            userId);
7285                }
7286                if (result == null || result.size() == 0) {
7287                    // the caller wants to resolve for a particular package; however, there
7288                    // were no installed results, so, try to find an ephemeral result
7289                    addEphemeral = !ephemeralDisabled
7290                            && isInstantAppAllowed(
7291                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
7292                    if (result == null) {
7293                        result = new ArrayList<>();
7294                    }
7295                }
7296            }
7297        }
7298        if (addEphemeral) {
7299            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
7300        }
7301        if (sortResult) {
7302            Collections.sort(result, mResolvePrioritySorter);
7303        }
7304        return applyPostResolutionFilter(
7305                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId);
7306    }
7307
7308    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7309            String resolvedType, int flags, int userId) {
7310        // first, check to see if we've got an instant app already installed
7311        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7312        ResolveInfo localInstantApp = null;
7313        boolean blockResolution = false;
7314        if (!alreadyResolvedLocally) {
7315            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7316                    flags
7317                        | PackageManager.GET_RESOLVED_FILTER
7318                        | PackageManager.MATCH_INSTANT
7319                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7320                    userId);
7321            for (int i = instantApps.size() - 1; i >= 0; --i) {
7322                final ResolveInfo info = instantApps.get(i);
7323                final String packageName = info.activityInfo.packageName;
7324                final PackageSetting ps = mSettings.mPackages.get(packageName);
7325                if (ps.getInstantApp(userId)) {
7326                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7327                    final int status = (int)(packedStatus >> 32);
7328                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7329                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7330                        // there's a local instant application installed, but, the user has
7331                        // chosen to never use it; skip resolution and don't acknowledge
7332                        // an instant application is even available
7333                        if (DEBUG_EPHEMERAL) {
7334                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7335                        }
7336                        blockResolution = true;
7337                        break;
7338                    } else {
7339                        // we have a locally installed instant application; skip resolution
7340                        // but acknowledge there's an instant application available
7341                        if (DEBUG_EPHEMERAL) {
7342                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7343                        }
7344                        localInstantApp = info;
7345                        break;
7346                    }
7347                }
7348            }
7349        }
7350        // no app installed, let's see if one's available
7351        AuxiliaryResolveInfo auxiliaryResponse = null;
7352        if (!blockResolution) {
7353            if (localInstantApp == null) {
7354                // we don't have an instant app locally, resolve externally
7355                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7356                final InstantAppRequest requestObject = new InstantAppRequest(
7357                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7358                        null /*callingPackage*/, userId, null /*verificationBundle*/);
7359                auxiliaryResponse =
7360                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7361                                mContext, mInstantAppResolverConnection, requestObject);
7362                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7363            } else {
7364                // we have an instant application locally, but, we can't admit that since
7365                // callers shouldn't be able to determine prior browsing. create a dummy
7366                // auxiliary response so the downstream code behaves as if there's an
7367                // instant application available externally. when it comes time to start
7368                // the instant application, we'll do the right thing.
7369                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7370                auxiliaryResponse = new AuxiliaryResolveInfo(
7371                        ai.packageName, null /*splitName*/, null /*failureActivity*/,
7372                        ai.versionCode, null /*failureIntent*/);
7373            }
7374        }
7375        if (auxiliaryResponse != null) {
7376            if (DEBUG_EPHEMERAL) {
7377                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7378            }
7379            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7380            final PackageSetting ps =
7381                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7382            if (ps != null) {
7383                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7384                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7385                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7386                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7387                // make sure this resolver is the default
7388                ephemeralInstaller.isDefault = true;
7389                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7390                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7391                // add a non-generic filter
7392                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7393                ephemeralInstaller.filter.addDataPath(
7394                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7395                ephemeralInstaller.isInstantAppAvailable = true;
7396                result.add(ephemeralInstaller);
7397            }
7398        }
7399        return result;
7400    }
7401
7402    private static class CrossProfileDomainInfo {
7403        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7404        ResolveInfo resolveInfo;
7405        /* Best domain verification status of the activities found in the other profile */
7406        int bestDomainVerificationStatus;
7407    }
7408
7409    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7410            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7411        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7412                sourceUserId)) {
7413            return null;
7414        }
7415        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7416                resolvedType, flags, parentUserId);
7417
7418        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7419            return null;
7420        }
7421        CrossProfileDomainInfo result = null;
7422        int size = resultTargetUser.size();
7423        for (int i = 0; i < size; i++) {
7424            ResolveInfo riTargetUser = resultTargetUser.get(i);
7425            // Intent filter verification is only for filters that specify a host. So don't return
7426            // those that handle all web uris.
7427            if (riTargetUser.handleAllWebDataURI) {
7428                continue;
7429            }
7430            String packageName = riTargetUser.activityInfo.packageName;
7431            PackageSetting ps = mSettings.mPackages.get(packageName);
7432            if (ps == null) {
7433                continue;
7434            }
7435            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7436            int status = (int)(verificationState >> 32);
7437            if (result == null) {
7438                result = new CrossProfileDomainInfo();
7439                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7440                        sourceUserId, parentUserId);
7441                result.bestDomainVerificationStatus = status;
7442            } else {
7443                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7444                        result.bestDomainVerificationStatus);
7445            }
7446        }
7447        // Don't consider matches with status NEVER across profiles.
7448        if (result != null && result.bestDomainVerificationStatus
7449                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7450            return null;
7451        }
7452        return result;
7453    }
7454
7455    /**
7456     * Verification statuses are ordered from the worse to the best, except for
7457     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7458     */
7459    private int bestDomainVerificationStatus(int status1, int status2) {
7460        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7461            return status2;
7462        }
7463        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7464            return status1;
7465        }
7466        return (int) MathUtils.max(status1, status2);
7467    }
7468
7469    private boolean isUserEnabled(int userId) {
7470        long callingId = Binder.clearCallingIdentity();
7471        try {
7472            UserInfo userInfo = sUserManager.getUserInfo(userId);
7473            return userInfo != null && userInfo.isEnabled();
7474        } finally {
7475            Binder.restoreCallingIdentity(callingId);
7476        }
7477    }
7478
7479    /**
7480     * Filter out activities with systemUserOnly flag set, when current user is not System.
7481     *
7482     * @return filtered list
7483     */
7484    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7485        if (userId == UserHandle.USER_SYSTEM) {
7486            return resolveInfos;
7487        }
7488        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7489            ResolveInfo info = resolveInfos.get(i);
7490            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7491                resolveInfos.remove(i);
7492            }
7493        }
7494        return resolveInfos;
7495    }
7496
7497    /**
7498     * Filters out ephemeral activities.
7499     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7500     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7501     *
7502     * @param resolveInfos The pre-filtered list of resolved activities
7503     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7504     *          is performed.
7505     * @return A filtered list of resolved activities.
7506     */
7507    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7508            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) {
7509        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7510            final ResolveInfo info = resolveInfos.get(i);
7511            // allow activities that are defined in the provided package
7512            if (allowDynamicSplits
7513                    && info.activityInfo.splitName != null
7514                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7515                            info.activityInfo.splitName)) {
7516                // requested activity is defined in a split that hasn't been installed yet.
7517                // add the installer to the resolve list
7518                if (DEBUG_INSTALL) {
7519                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
7520                }
7521                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7522                final ComponentName installFailureActivity = findInstallFailureActivity(
7523                        info.activityInfo.packageName,  filterCallingUid, userId);
7524                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7525                        info.activityInfo.packageName, info.activityInfo.splitName,
7526                        installFailureActivity,
7527                        info.activityInfo.applicationInfo.versionCode,
7528                        null /*failureIntent*/);
7529                // make sure this resolver is the default
7530                installerInfo.isDefault = true;
7531                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7532                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7533                // add a non-generic filter
7534                installerInfo.filter = new IntentFilter();
7535                // load resources from the correct package
7536                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7537                resolveInfos.set(i, installerInfo);
7538                continue;
7539            }
7540            // caller is a full app, don't need to apply any other filtering
7541            if (ephemeralPkgName == null) {
7542                continue;
7543            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7544                // caller is same app; don't need to apply any other filtering
7545                continue;
7546            }
7547            // allow activities that have been explicitly exposed to ephemeral apps
7548            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7549            if (!isEphemeralApp
7550                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7551                continue;
7552            }
7553            resolveInfos.remove(i);
7554        }
7555        return resolveInfos;
7556    }
7557
7558    /**
7559     * Returns the activity component that can handle install failures.
7560     * <p>By default, the instant application installer handles failures. However, an
7561     * application may want to handle failures on its own. Applications do this by
7562     * creating an activity with an intent filter that handles the action
7563     * {@link Intent#ACTION_INSTALL_FAILURE}.
7564     */
7565    private @Nullable ComponentName findInstallFailureActivity(
7566            String packageName, int filterCallingUid, int userId) {
7567        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
7568        failureActivityIntent.setPackage(packageName);
7569        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
7570        final List<ResolveInfo> result = queryIntentActivitiesInternal(
7571                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
7572                false /*resolveForStart*/, false /*allowDynamicSplits*/);
7573        final int NR = result.size();
7574        if (NR > 0) {
7575            for (int i = 0; i < NR; i++) {
7576                final ResolveInfo info = result.get(i);
7577                if (info.activityInfo.splitName != null) {
7578                    continue;
7579                }
7580                return new ComponentName(packageName, info.activityInfo.name);
7581            }
7582        }
7583        return null;
7584    }
7585
7586    /**
7587     * @param resolveInfos list of resolve infos in descending priority order
7588     * @return if the list contains a resolve info with non-negative priority
7589     */
7590    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7591        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7592    }
7593
7594    private static boolean hasWebURI(Intent intent) {
7595        if (intent.getData() == null) {
7596            return false;
7597        }
7598        final String scheme = intent.getScheme();
7599        if (TextUtils.isEmpty(scheme)) {
7600            return false;
7601        }
7602        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7603    }
7604
7605    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7606            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7607            int userId) {
7608        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7609
7610        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7611            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7612                    candidates.size());
7613        }
7614
7615        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7616        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7617        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7618        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7619        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7620        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7621
7622        synchronized (mPackages) {
7623            final int count = candidates.size();
7624            // First, try to use linked apps. Partition the candidates into four lists:
7625            // one for the final results, one for the "do not use ever", one for "undefined status"
7626            // and finally one for "browser app type".
7627            for (int n=0; n<count; n++) {
7628                ResolveInfo info = candidates.get(n);
7629                String packageName = info.activityInfo.packageName;
7630                PackageSetting ps = mSettings.mPackages.get(packageName);
7631                if (ps != null) {
7632                    // Add to the special match all list (Browser use case)
7633                    if (info.handleAllWebDataURI) {
7634                        matchAllList.add(info);
7635                        continue;
7636                    }
7637                    // Try to get the status from User settings first
7638                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7639                    int status = (int)(packedStatus >> 32);
7640                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7641                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7642                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7643                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7644                                    + " : linkgen=" + linkGeneration);
7645                        }
7646                        // Use link-enabled generation as preferredOrder, i.e.
7647                        // prefer newly-enabled over earlier-enabled.
7648                        info.preferredOrder = linkGeneration;
7649                        alwaysList.add(info);
7650                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7651                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7652                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7653                        }
7654                        neverList.add(info);
7655                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7656                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7657                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7658                        }
7659                        alwaysAskList.add(info);
7660                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7661                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7662                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7663                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7664                        }
7665                        undefinedList.add(info);
7666                    }
7667                }
7668            }
7669
7670            // We'll want to include browser possibilities in a few cases
7671            boolean includeBrowser = false;
7672
7673            // First try to add the "always" resolution(s) for the current user, if any
7674            if (alwaysList.size() > 0) {
7675                result.addAll(alwaysList);
7676            } else {
7677                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7678                result.addAll(undefinedList);
7679                // Maybe add one for the other profile.
7680                if (xpDomainInfo != null && (
7681                        xpDomainInfo.bestDomainVerificationStatus
7682                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7683                    result.add(xpDomainInfo.resolveInfo);
7684                }
7685                includeBrowser = true;
7686            }
7687
7688            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7689            // If there were 'always' entries their preferred order has been set, so we also
7690            // back that off to make the alternatives equivalent
7691            if (alwaysAskList.size() > 0) {
7692                for (ResolveInfo i : result) {
7693                    i.preferredOrder = 0;
7694                }
7695                result.addAll(alwaysAskList);
7696                includeBrowser = true;
7697            }
7698
7699            if (includeBrowser) {
7700                // Also add browsers (all of them or only the default one)
7701                if (DEBUG_DOMAIN_VERIFICATION) {
7702                    Slog.v(TAG, "   ...including browsers in candidate set");
7703                }
7704                if ((matchFlags & MATCH_ALL) != 0) {
7705                    result.addAll(matchAllList);
7706                } else {
7707                    // Browser/generic handling case.  If there's a default browser, go straight
7708                    // to that (but only if there is no other higher-priority match).
7709                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7710                    int maxMatchPrio = 0;
7711                    ResolveInfo defaultBrowserMatch = null;
7712                    final int numCandidates = matchAllList.size();
7713                    for (int n = 0; n < numCandidates; n++) {
7714                        ResolveInfo info = matchAllList.get(n);
7715                        // track the highest overall match priority...
7716                        if (info.priority > maxMatchPrio) {
7717                            maxMatchPrio = info.priority;
7718                        }
7719                        // ...and the highest-priority default browser match
7720                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7721                            if (defaultBrowserMatch == null
7722                                    || (defaultBrowserMatch.priority < info.priority)) {
7723                                if (debug) {
7724                                    Slog.v(TAG, "Considering default browser match " + info);
7725                                }
7726                                defaultBrowserMatch = info;
7727                            }
7728                        }
7729                    }
7730                    if (defaultBrowserMatch != null
7731                            && defaultBrowserMatch.priority >= maxMatchPrio
7732                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7733                    {
7734                        if (debug) {
7735                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7736                        }
7737                        result.add(defaultBrowserMatch);
7738                    } else {
7739                        result.addAll(matchAllList);
7740                    }
7741                }
7742
7743                // If there is nothing selected, add all candidates and remove the ones that the user
7744                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7745                if (result.size() == 0) {
7746                    result.addAll(candidates);
7747                    result.removeAll(neverList);
7748                }
7749            }
7750        }
7751        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7752            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7753                    result.size());
7754            for (ResolveInfo info : result) {
7755                Slog.v(TAG, "  + " + info.activityInfo);
7756            }
7757        }
7758        return result;
7759    }
7760
7761    // Returns a packed value as a long:
7762    //
7763    // high 'int'-sized word: link status: undefined/ask/never/always.
7764    // low 'int'-sized word: relative priority among 'always' results.
7765    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7766        long result = ps.getDomainVerificationStatusForUser(userId);
7767        // if none available, get the master status
7768        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7769            if (ps.getIntentFilterVerificationInfo() != null) {
7770                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7771            }
7772        }
7773        return result;
7774    }
7775
7776    private ResolveInfo querySkipCurrentProfileIntents(
7777            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7778            int flags, int sourceUserId) {
7779        if (matchingFilters != null) {
7780            int size = matchingFilters.size();
7781            for (int i = 0; i < size; i ++) {
7782                CrossProfileIntentFilter filter = matchingFilters.get(i);
7783                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7784                    // Checking if there are activities in the target user that can handle the
7785                    // intent.
7786                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7787                            resolvedType, flags, sourceUserId);
7788                    if (resolveInfo != null) {
7789                        return resolveInfo;
7790                    }
7791                }
7792            }
7793        }
7794        return null;
7795    }
7796
7797    // Return matching ResolveInfo in target user if any.
7798    private ResolveInfo queryCrossProfileIntents(
7799            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7800            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7801        if (matchingFilters != null) {
7802            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7803            // match the same intent. For performance reasons, it is better not to
7804            // run queryIntent twice for the same userId
7805            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7806            int size = matchingFilters.size();
7807            for (int i = 0; i < size; i++) {
7808                CrossProfileIntentFilter filter = matchingFilters.get(i);
7809                int targetUserId = filter.getTargetUserId();
7810                boolean skipCurrentProfile =
7811                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7812                boolean skipCurrentProfileIfNoMatchFound =
7813                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7814                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7815                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7816                    // Checking if there are activities in the target user that can handle the
7817                    // intent.
7818                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7819                            resolvedType, flags, sourceUserId);
7820                    if (resolveInfo != null) return resolveInfo;
7821                    alreadyTriedUserIds.put(targetUserId, true);
7822                }
7823            }
7824        }
7825        return null;
7826    }
7827
7828    /**
7829     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7830     * will forward the intent to the filter's target user.
7831     * Otherwise, returns null.
7832     */
7833    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7834            String resolvedType, int flags, int sourceUserId) {
7835        int targetUserId = filter.getTargetUserId();
7836        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7837                resolvedType, flags, targetUserId);
7838        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7839            // If all the matches in the target profile are suspended, return null.
7840            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7841                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7842                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7843                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7844                            targetUserId);
7845                }
7846            }
7847        }
7848        return null;
7849    }
7850
7851    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7852            int sourceUserId, int targetUserId) {
7853        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7854        long ident = Binder.clearCallingIdentity();
7855        boolean targetIsProfile;
7856        try {
7857            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7858        } finally {
7859            Binder.restoreCallingIdentity(ident);
7860        }
7861        String className;
7862        if (targetIsProfile) {
7863            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7864        } else {
7865            className = FORWARD_INTENT_TO_PARENT;
7866        }
7867        ComponentName forwardingActivityComponentName = new ComponentName(
7868                mAndroidApplication.packageName, className);
7869        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7870                sourceUserId);
7871        if (!targetIsProfile) {
7872            forwardingActivityInfo.showUserIcon = targetUserId;
7873            forwardingResolveInfo.noResourceId = true;
7874        }
7875        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7876        forwardingResolveInfo.priority = 0;
7877        forwardingResolveInfo.preferredOrder = 0;
7878        forwardingResolveInfo.match = 0;
7879        forwardingResolveInfo.isDefault = true;
7880        forwardingResolveInfo.filter = filter;
7881        forwardingResolveInfo.targetUserId = targetUserId;
7882        return forwardingResolveInfo;
7883    }
7884
7885    @Override
7886    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7887            Intent[] specifics, String[] specificTypes, Intent intent,
7888            String resolvedType, int flags, int userId) {
7889        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7890                specificTypes, intent, resolvedType, flags, userId));
7891    }
7892
7893    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7894            Intent[] specifics, String[] specificTypes, Intent intent,
7895            String resolvedType, int flags, int userId) {
7896        if (!sUserManager.exists(userId)) return Collections.emptyList();
7897        final int callingUid = Binder.getCallingUid();
7898        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7899                false /*includeInstantApps*/);
7900        enforceCrossUserPermission(callingUid, userId,
7901                false /*requireFullPermission*/, false /*checkShell*/,
7902                "query intent activity options");
7903        final String resultsAction = intent.getAction();
7904
7905        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7906                | PackageManager.GET_RESOLVED_FILTER, userId);
7907
7908        if (DEBUG_INTENT_MATCHING) {
7909            Log.v(TAG, "Query " + intent + ": " + results);
7910        }
7911
7912        int specificsPos = 0;
7913        int N;
7914
7915        // todo: note that the algorithm used here is O(N^2).  This
7916        // isn't a problem in our current environment, but if we start running
7917        // into situations where we have more than 5 or 10 matches then this
7918        // should probably be changed to something smarter...
7919
7920        // First we go through and resolve each of the specific items
7921        // that were supplied, taking care of removing any corresponding
7922        // duplicate items in the generic resolve list.
7923        if (specifics != null) {
7924            for (int i=0; i<specifics.length; i++) {
7925                final Intent sintent = specifics[i];
7926                if (sintent == null) {
7927                    continue;
7928                }
7929
7930                if (DEBUG_INTENT_MATCHING) {
7931                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7932                }
7933
7934                String action = sintent.getAction();
7935                if (resultsAction != null && resultsAction.equals(action)) {
7936                    // If this action was explicitly requested, then don't
7937                    // remove things that have it.
7938                    action = null;
7939                }
7940
7941                ResolveInfo ri = null;
7942                ActivityInfo ai = null;
7943
7944                ComponentName comp = sintent.getComponent();
7945                if (comp == null) {
7946                    ri = resolveIntent(
7947                        sintent,
7948                        specificTypes != null ? specificTypes[i] : null,
7949                            flags, userId);
7950                    if (ri == null) {
7951                        continue;
7952                    }
7953                    if (ri == mResolveInfo) {
7954                        // ACK!  Must do something better with this.
7955                    }
7956                    ai = ri.activityInfo;
7957                    comp = new ComponentName(ai.applicationInfo.packageName,
7958                            ai.name);
7959                } else {
7960                    ai = getActivityInfo(comp, flags, userId);
7961                    if (ai == null) {
7962                        continue;
7963                    }
7964                }
7965
7966                // Look for any generic query activities that are duplicates
7967                // of this specific one, and remove them from the results.
7968                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7969                N = results.size();
7970                int j;
7971                for (j=specificsPos; j<N; j++) {
7972                    ResolveInfo sri = results.get(j);
7973                    if ((sri.activityInfo.name.equals(comp.getClassName())
7974                            && sri.activityInfo.applicationInfo.packageName.equals(
7975                                    comp.getPackageName()))
7976                        || (action != null && sri.filter.matchAction(action))) {
7977                        results.remove(j);
7978                        if (DEBUG_INTENT_MATCHING) Log.v(
7979                            TAG, "Removing duplicate item from " + j
7980                            + " due to specific " + specificsPos);
7981                        if (ri == null) {
7982                            ri = sri;
7983                        }
7984                        j--;
7985                        N--;
7986                    }
7987                }
7988
7989                // Add this specific item to its proper place.
7990                if (ri == null) {
7991                    ri = new ResolveInfo();
7992                    ri.activityInfo = ai;
7993                }
7994                results.add(specificsPos, ri);
7995                ri.specificIndex = i;
7996                specificsPos++;
7997            }
7998        }
7999
8000        // Now we go through the remaining generic results and remove any
8001        // duplicate actions that are found here.
8002        N = results.size();
8003        for (int i=specificsPos; i<N-1; i++) {
8004            final ResolveInfo rii = results.get(i);
8005            if (rii.filter == null) {
8006                continue;
8007            }
8008
8009            // Iterate over all of the actions of this result's intent
8010            // filter...  typically this should be just one.
8011            final Iterator<String> it = rii.filter.actionsIterator();
8012            if (it == null) {
8013                continue;
8014            }
8015            while (it.hasNext()) {
8016                final String action = it.next();
8017                if (resultsAction != null && resultsAction.equals(action)) {
8018                    // If this action was explicitly requested, then don't
8019                    // remove things that have it.
8020                    continue;
8021                }
8022                for (int j=i+1; j<N; j++) {
8023                    final ResolveInfo rij = results.get(j);
8024                    if (rij.filter != null && rij.filter.hasAction(action)) {
8025                        results.remove(j);
8026                        if (DEBUG_INTENT_MATCHING) Log.v(
8027                            TAG, "Removing duplicate item from " + j
8028                            + " due to action " + action + " at " + i);
8029                        j--;
8030                        N--;
8031                    }
8032                }
8033            }
8034
8035            // If the caller didn't request filter information, drop it now
8036            // so we don't have to marshall/unmarshall it.
8037            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8038                rii.filter = null;
8039            }
8040        }
8041
8042        // Filter out the caller activity if so requested.
8043        if (caller != null) {
8044            N = results.size();
8045            for (int i=0; i<N; i++) {
8046                ActivityInfo ainfo = results.get(i).activityInfo;
8047                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
8048                        && caller.getClassName().equals(ainfo.name)) {
8049                    results.remove(i);
8050                    break;
8051                }
8052            }
8053        }
8054
8055        // If the caller didn't request filter information,
8056        // drop them now so we don't have to
8057        // marshall/unmarshall it.
8058        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8059            N = results.size();
8060            for (int i=0; i<N; i++) {
8061                results.get(i).filter = null;
8062            }
8063        }
8064
8065        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
8066        return results;
8067    }
8068
8069    @Override
8070    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
8071            String resolvedType, int flags, int userId) {
8072        return new ParceledListSlice<>(
8073                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
8074                        false /*allowDynamicSplits*/));
8075    }
8076
8077    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
8078            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
8079        if (!sUserManager.exists(userId)) return Collections.emptyList();
8080        final int callingUid = Binder.getCallingUid();
8081        enforceCrossUserPermission(callingUid, userId,
8082                false /*requireFullPermission*/, false /*checkShell*/,
8083                "query intent receivers");
8084        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8085        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8086                false /*includeInstantApps*/);
8087        ComponentName comp = intent.getComponent();
8088        if (comp == null) {
8089            if (intent.getSelector() != null) {
8090                intent = intent.getSelector();
8091                comp = intent.getComponent();
8092            }
8093        }
8094        if (comp != null) {
8095            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8096            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
8097            if (ai != null) {
8098                // When specifying an explicit component, we prevent the activity from being
8099                // used when either 1) the calling package is normal and the activity is within
8100                // an instant application or 2) the calling package is ephemeral and the
8101                // activity is not visible to instant applications.
8102                final boolean matchInstantApp =
8103                        (flags & PackageManager.MATCH_INSTANT) != 0;
8104                final boolean matchVisibleToInstantAppOnly =
8105                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8106                final boolean matchExplicitlyVisibleOnly =
8107                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
8108                final boolean isCallerInstantApp =
8109                        instantAppPkgName != null;
8110                final boolean isTargetSameInstantApp =
8111                        comp.getPackageName().equals(instantAppPkgName);
8112                final boolean isTargetInstantApp =
8113                        (ai.applicationInfo.privateFlags
8114                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8115                final boolean isTargetVisibleToInstantApp =
8116                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
8117                final boolean isTargetExplicitlyVisibleToInstantApp =
8118                        isTargetVisibleToInstantApp
8119                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
8120                final boolean isTargetHiddenFromInstantApp =
8121                        !isTargetVisibleToInstantApp
8122                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
8123                final boolean blockResolution =
8124                        !isTargetSameInstantApp
8125                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8126                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8127                                        && isTargetHiddenFromInstantApp));
8128                if (!blockResolution) {
8129                    ResolveInfo ri = new ResolveInfo();
8130                    ri.activityInfo = ai;
8131                    list.add(ri);
8132                }
8133            }
8134            return applyPostResolutionFilter(
8135                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8136        }
8137
8138        // reader
8139        synchronized (mPackages) {
8140            String pkgName = intent.getPackage();
8141            if (pkgName == null) {
8142                final List<ResolveInfo> result =
8143                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
8144                return applyPostResolutionFilter(
8145                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8146            }
8147            final PackageParser.Package pkg = mPackages.get(pkgName);
8148            if (pkg != null) {
8149                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
8150                        intent, resolvedType, flags, pkg.receivers, userId);
8151                return applyPostResolutionFilter(
8152                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId);
8153            }
8154            return Collections.emptyList();
8155        }
8156    }
8157
8158    @Override
8159    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
8160        final int callingUid = Binder.getCallingUid();
8161        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
8162    }
8163
8164    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
8165            int userId, int callingUid) {
8166        if (!sUserManager.exists(userId)) return null;
8167        flags = updateFlagsForResolve(
8168                flags, userId, intent, callingUid, false /*includeInstantApps*/);
8169        List<ResolveInfo> query = queryIntentServicesInternal(
8170                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
8171        if (query != null) {
8172            if (query.size() >= 1) {
8173                // If there is more than one service with the same priority,
8174                // just arbitrarily pick the first one.
8175                return query.get(0);
8176            }
8177        }
8178        return null;
8179    }
8180
8181    @Override
8182    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
8183            String resolvedType, int flags, int userId) {
8184        final int callingUid = Binder.getCallingUid();
8185        return new ParceledListSlice<>(queryIntentServicesInternal(
8186                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
8187    }
8188
8189    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
8190            String resolvedType, int flags, int userId, int callingUid,
8191            boolean includeInstantApps) {
8192        if (!sUserManager.exists(userId)) return Collections.emptyList();
8193        enforceCrossUserPermission(callingUid, userId,
8194                false /*requireFullPermission*/, false /*checkShell*/,
8195                "query intent receivers");
8196        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8197        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
8198        ComponentName comp = intent.getComponent();
8199        if (comp == null) {
8200            if (intent.getSelector() != null) {
8201                intent = intent.getSelector();
8202                comp = intent.getComponent();
8203            }
8204        }
8205        if (comp != null) {
8206            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8207            final ServiceInfo si = getServiceInfo(comp, flags, userId);
8208            if (si != null) {
8209                // When specifying an explicit component, we prevent the service from being
8210                // used when either 1) the service is in an instant application and the
8211                // caller is not the same instant application or 2) the calling package is
8212                // ephemeral and the activity is not visible to ephemeral applications.
8213                final boolean matchInstantApp =
8214                        (flags & PackageManager.MATCH_INSTANT) != 0;
8215                final boolean matchVisibleToInstantAppOnly =
8216                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8217                final boolean isCallerInstantApp =
8218                        instantAppPkgName != null;
8219                final boolean isTargetSameInstantApp =
8220                        comp.getPackageName().equals(instantAppPkgName);
8221                final boolean isTargetInstantApp =
8222                        (si.applicationInfo.privateFlags
8223                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8224                final boolean isTargetHiddenFromInstantApp =
8225                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8226                final boolean blockResolution =
8227                        !isTargetSameInstantApp
8228                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8229                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8230                                        && isTargetHiddenFromInstantApp));
8231                if (!blockResolution) {
8232                    final ResolveInfo ri = new ResolveInfo();
8233                    ri.serviceInfo = si;
8234                    list.add(ri);
8235                }
8236            }
8237            return list;
8238        }
8239
8240        // reader
8241        synchronized (mPackages) {
8242            String pkgName = intent.getPackage();
8243            if (pkgName == null) {
8244                return applyPostServiceResolutionFilter(
8245                        mServices.queryIntent(intent, resolvedType, flags, userId),
8246                        instantAppPkgName);
8247            }
8248            final PackageParser.Package pkg = mPackages.get(pkgName);
8249            if (pkg != null) {
8250                return applyPostServiceResolutionFilter(
8251                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
8252                                userId),
8253                        instantAppPkgName);
8254            }
8255            return Collections.emptyList();
8256        }
8257    }
8258
8259    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
8260            String instantAppPkgName) {
8261        if (instantAppPkgName == null) {
8262            return resolveInfos;
8263        }
8264        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8265            final ResolveInfo info = resolveInfos.get(i);
8266            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
8267            // allow services that are defined in the provided package
8268            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
8269                if (info.serviceInfo.splitName != null
8270                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
8271                                info.serviceInfo.splitName)) {
8272                    // requested service is defined in a split that hasn't been installed yet.
8273                    // add the installer to the resolve list
8274                    if (DEBUG_EPHEMERAL) {
8275                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8276                    }
8277                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8278                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8279                            info.serviceInfo.packageName, info.serviceInfo.splitName,
8280                            null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
8281                            null /*failureIntent*/);
8282                    // make sure this resolver is the default
8283                    installerInfo.isDefault = true;
8284                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8285                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8286                    // add a non-generic filter
8287                    installerInfo.filter = new IntentFilter();
8288                    // load resources from the correct package
8289                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8290                    resolveInfos.set(i, installerInfo);
8291                }
8292                continue;
8293            }
8294            // allow services that have been explicitly exposed to ephemeral apps
8295            if (!isEphemeralApp
8296                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8297                continue;
8298            }
8299            resolveInfos.remove(i);
8300        }
8301        return resolveInfos;
8302    }
8303
8304    @Override
8305    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
8306            String resolvedType, int flags, int userId) {
8307        return new ParceledListSlice<>(
8308                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
8309    }
8310
8311    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
8312            Intent intent, String resolvedType, int flags, int userId) {
8313        if (!sUserManager.exists(userId)) return Collections.emptyList();
8314        final int callingUid = Binder.getCallingUid();
8315        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8316        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8317                false /*includeInstantApps*/);
8318        ComponentName comp = intent.getComponent();
8319        if (comp == null) {
8320            if (intent.getSelector() != null) {
8321                intent = intent.getSelector();
8322                comp = intent.getComponent();
8323            }
8324        }
8325        if (comp != null) {
8326            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8327            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8328            if (pi != null) {
8329                // When specifying an explicit component, we prevent the provider from being
8330                // used when either 1) the provider is in an instant application and the
8331                // caller is not the same instant application or 2) the calling package is an
8332                // instant application and the provider is not visible to instant applications.
8333                final boolean matchInstantApp =
8334                        (flags & PackageManager.MATCH_INSTANT) != 0;
8335                final boolean matchVisibleToInstantAppOnly =
8336                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8337                final boolean isCallerInstantApp =
8338                        instantAppPkgName != null;
8339                final boolean isTargetSameInstantApp =
8340                        comp.getPackageName().equals(instantAppPkgName);
8341                final boolean isTargetInstantApp =
8342                        (pi.applicationInfo.privateFlags
8343                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8344                final boolean isTargetHiddenFromInstantApp =
8345                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8346                final boolean blockResolution =
8347                        !isTargetSameInstantApp
8348                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8349                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8350                                        && isTargetHiddenFromInstantApp));
8351                if (!blockResolution) {
8352                    final ResolveInfo ri = new ResolveInfo();
8353                    ri.providerInfo = pi;
8354                    list.add(ri);
8355                }
8356            }
8357            return list;
8358        }
8359
8360        // reader
8361        synchronized (mPackages) {
8362            String pkgName = intent.getPackage();
8363            if (pkgName == null) {
8364                return applyPostContentProviderResolutionFilter(
8365                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8366                        instantAppPkgName);
8367            }
8368            final PackageParser.Package pkg = mPackages.get(pkgName);
8369            if (pkg != null) {
8370                return applyPostContentProviderResolutionFilter(
8371                        mProviders.queryIntentForPackage(
8372                        intent, resolvedType, flags, pkg.providers, userId),
8373                        instantAppPkgName);
8374            }
8375            return Collections.emptyList();
8376        }
8377    }
8378
8379    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8380            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8381        if (instantAppPkgName == null) {
8382            return resolveInfos;
8383        }
8384        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8385            final ResolveInfo info = resolveInfos.get(i);
8386            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8387            // allow providers that are defined in the provided package
8388            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8389                if (info.providerInfo.splitName != null
8390                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8391                                info.providerInfo.splitName)) {
8392                    // requested provider is defined in a split that hasn't been installed yet.
8393                    // add the installer to the resolve list
8394                    if (DEBUG_EPHEMERAL) {
8395                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8396                    }
8397                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8398                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8399                            info.providerInfo.packageName, info.providerInfo.splitName,
8400                            null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
8401                            null /*failureIntent*/);
8402                    // make sure this resolver is the default
8403                    installerInfo.isDefault = true;
8404                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8405                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8406                    // add a non-generic filter
8407                    installerInfo.filter = new IntentFilter();
8408                    // load resources from the correct package
8409                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8410                    resolveInfos.set(i, installerInfo);
8411                }
8412                continue;
8413            }
8414            // allow providers that have been explicitly exposed to instant applications
8415            if (!isEphemeralApp
8416                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8417                continue;
8418            }
8419            resolveInfos.remove(i);
8420        }
8421        return resolveInfos;
8422    }
8423
8424    @Override
8425    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8426        final int callingUid = Binder.getCallingUid();
8427        if (getInstantAppPackageName(callingUid) != null) {
8428            return ParceledListSlice.emptyList();
8429        }
8430        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8431        flags = updateFlagsForPackage(flags, userId, null);
8432        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8433        enforceCrossUserPermission(callingUid, userId,
8434                true /* requireFullPermission */, false /* checkShell */,
8435                "get installed packages");
8436
8437        // writer
8438        synchronized (mPackages) {
8439            ArrayList<PackageInfo> list;
8440            if (listUninstalled) {
8441                list = new ArrayList<>(mSettings.mPackages.size());
8442                for (PackageSetting ps : mSettings.mPackages.values()) {
8443                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8444                        continue;
8445                    }
8446                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8447                        return null;
8448                    }
8449                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8450                    if (pi != null) {
8451                        list.add(pi);
8452                    }
8453                }
8454            } else {
8455                list = new ArrayList<>(mPackages.size());
8456                for (PackageParser.Package p : mPackages.values()) {
8457                    final PackageSetting ps = (PackageSetting) p.mExtras;
8458                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8459                        continue;
8460                    }
8461                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8462                        return null;
8463                    }
8464                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8465                            p.mExtras, flags, userId);
8466                    if (pi != null) {
8467                        list.add(pi);
8468                    }
8469                }
8470            }
8471
8472            return new ParceledListSlice<>(list);
8473        }
8474    }
8475
8476    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8477            String[] permissions, boolean[] tmp, int flags, int userId) {
8478        int numMatch = 0;
8479        final PermissionsState permissionsState = ps.getPermissionsState();
8480        for (int i=0; i<permissions.length; i++) {
8481            final String permission = permissions[i];
8482            if (permissionsState.hasPermission(permission, userId)) {
8483                tmp[i] = true;
8484                numMatch++;
8485            } else {
8486                tmp[i] = false;
8487            }
8488        }
8489        if (numMatch == 0) {
8490            return;
8491        }
8492        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8493
8494        // The above might return null in cases of uninstalled apps or install-state
8495        // skew across users/profiles.
8496        if (pi != null) {
8497            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8498                if (numMatch == permissions.length) {
8499                    pi.requestedPermissions = permissions;
8500                } else {
8501                    pi.requestedPermissions = new String[numMatch];
8502                    numMatch = 0;
8503                    for (int i=0; i<permissions.length; i++) {
8504                        if (tmp[i]) {
8505                            pi.requestedPermissions[numMatch] = permissions[i];
8506                            numMatch++;
8507                        }
8508                    }
8509                }
8510            }
8511            list.add(pi);
8512        }
8513    }
8514
8515    @Override
8516    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8517            String[] permissions, int flags, int userId) {
8518        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8519        flags = updateFlagsForPackage(flags, userId, permissions);
8520        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8521                true /* requireFullPermission */, false /* checkShell */,
8522                "get packages holding permissions");
8523        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8524
8525        // writer
8526        synchronized (mPackages) {
8527            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8528            boolean[] tmpBools = new boolean[permissions.length];
8529            if (listUninstalled) {
8530                for (PackageSetting ps : mSettings.mPackages.values()) {
8531                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8532                            userId);
8533                }
8534            } else {
8535                for (PackageParser.Package pkg : mPackages.values()) {
8536                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8537                    if (ps != null) {
8538                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8539                                userId);
8540                    }
8541                }
8542            }
8543
8544            return new ParceledListSlice<PackageInfo>(list);
8545        }
8546    }
8547
8548    @Override
8549    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8550        final int callingUid = Binder.getCallingUid();
8551        if (getInstantAppPackageName(callingUid) != null) {
8552            return ParceledListSlice.emptyList();
8553        }
8554        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8555        flags = updateFlagsForApplication(flags, userId, null);
8556        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8557
8558        // writer
8559        synchronized (mPackages) {
8560            ArrayList<ApplicationInfo> list;
8561            if (listUninstalled) {
8562                list = new ArrayList<>(mSettings.mPackages.size());
8563                for (PackageSetting ps : mSettings.mPackages.values()) {
8564                    ApplicationInfo ai;
8565                    int effectiveFlags = flags;
8566                    if (ps.isSystem()) {
8567                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8568                    }
8569                    if (ps.pkg != null) {
8570                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8571                            continue;
8572                        }
8573                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8574                            return null;
8575                        }
8576                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8577                                ps.readUserState(userId), userId);
8578                        if (ai != null) {
8579                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8580                        }
8581                    } else {
8582                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8583                        // and already converts to externally visible package name
8584                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8585                                callingUid, effectiveFlags, userId);
8586                    }
8587                    if (ai != null) {
8588                        list.add(ai);
8589                    }
8590                }
8591            } else {
8592                list = new ArrayList<>(mPackages.size());
8593                for (PackageParser.Package p : mPackages.values()) {
8594                    if (p.mExtras != null) {
8595                        PackageSetting ps = (PackageSetting) p.mExtras;
8596                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8597                            continue;
8598                        }
8599                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8600                            return null;
8601                        }
8602                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8603                                ps.readUserState(userId), userId);
8604                        if (ai != null) {
8605                            ai.packageName = resolveExternalPackageNameLPr(p);
8606                            list.add(ai);
8607                        }
8608                    }
8609                }
8610            }
8611
8612            return new ParceledListSlice<>(list);
8613        }
8614    }
8615
8616    @Override
8617    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8618        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8619            return null;
8620        }
8621        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8622            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8623                    "getEphemeralApplications");
8624        }
8625        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8626                true /* requireFullPermission */, false /* checkShell */,
8627                "getEphemeralApplications");
8628        synchronized (mPackages) {
8629            List<InstantAppInfo> instantApps = mInstantAppRegistry
8630                    .getInstantAppsLPr(userId);
8631            if (instantApps != null) {
8632                return new ParceledListSlice<>(instantApps);
8633            }
8634        }
8635        return null;
8636    }
8637
8638    @Override
8639    public boolean isInstantApp(String packageName, int userId) {
8640        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8641                true /* requireFullPermission */, false /* checkShell */,
8642                "isInstantApp");
8643        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8644            return false;
8645        }
8646
8647        synchronized (mPackages) {
8648            int callingUid = Binder.getCallingUid();
8649            if (Process.isIsolated(callingUid)) {
8650                callingUid = mIsolatedOwners.get(callingUid);
8651            }
8652            final PackageSetting ps = mSettings.mPackages.get(packageName);
8653            PackageParser.Package pkg = mPackages.get(packageName);
8654            final boolean returnAllowed =
8655                    ps != null
8656                    && (isCallerSameApp(packageName, callingUid)
8657                            || canViewInstantApps(callingUid, userId)
8658                            || mInstantAppRegistry.isInstantAccessGranted(
8659                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8660            if (returnAllowed) {
8661                return ps.getInstantApp(userId);
8662            }
8663        }
8664        return false;
8665    }
8666
8667    @Override
8668    public byte[] getInstantAppCookie(String packageName, int userId) {
8669        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8670            return null;
8671        }
8672
8673        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8674                true /* requireFullPermission */, false /* checkShell */,
8675                "getInstantAppCookie");
8676        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8677            return null;
8678        }
8679        synchronized (mPackages) {
8680            return mInstantAppRegistry.getInstantAppCookieLPw(
8681                    packageName, userId);
8682        }
8683    }
8684
8685    @Override
8686    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8687        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8688            return true;
8689        }
8690
8691        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8692                true /* requireFullPermission */, true /* checkShell */,
8693                "setInstantAppCookie");
8694        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8695            return false;
8696        }
8697        synchronized (mPackages) {
8698            return mInstantAppRegistry.setInstantAppCookieLPw(
8699                    packageName, cookie, userId);
8700        }
8701    }
8702
8703    @Override
8704    public Bitmap getInstantAppIcon(String packageName, int userId) {
8705        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8706            return null;
8707        }
8708
8709        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8710            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8711                    "getInstantAppIcon");
8712        }
8713        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8714                true /* requireFullPermission */, false /* checkShell */,
8715                "getInstantAppIcon");
8716
8717        synchronized (mPackages) {
8718            return mInstantAppRegistry.getInstantAppIconLPw(
8719                    packageName, userId);
8720        }
8721    }
8722
8723    private boolean isCallerSameApp(String packageName, int uid) {
8724        PackageParser.Package pkg = mPackages.get(packageName);
8725        return pkg != null
8726                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8727    }
8728
8729    @Override
8730    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8731        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8732            return ParceledListSlice.emptyList();
8733        }
8734        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8735    }
8736
8737    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8738        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8739
8740        // reader
8741        synchronized (mPackages) {
8742            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8743            final int userId = UserHandle.getCallingUserId();
8744            while (i.hasNext()) {
8745                final PackageParser.Package p = i.next();
8746                if (p.applicationInfo == null) continue;
8747
8748                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8749                        && !p.applicationInfo.isDirectBootAware();
8750                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8751                        && p.applicationInfo.isDirectBootAware();
8752
8753                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8754                        && (!mSafeMode || isSystemApp(p))
8755                        && (matchesUnaware || matchesAware)) {
8756                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8757                    if (ps != null) {
8758                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8759                                ps.readUserState(userId), userId);
8760                        if (ai != null) {
8761                            finalList.add(ai);
8762                        }
8763                    }
8764                }
8765            }
8766        }
8767
8768        return finalList;
8769    }
8770
8771    @Override
8772    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8773        if (!sUserManager.exists(userId)) return null;
8774        flags = updateFlagsForComponent(flags, userId, name);
8775        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8776        // reader
8777        synchronized (mPackages) {
8778            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8779            PackageSetting ps = provider != null
8780                    ? mSettings.mPackages.get(provider.owner.packageName)
8781                    : null;
8782            if (ps != null) {
8783                final boolean isInstantApp = ps.getInstantApp(userId);
8784                // normal application; filter out instant application provider
8785                if (instantAppPkgName == null && isInstantApp) {
8786                    return null;
8787                }
8788                // instant application; filter out other instant applications
8789                if (instantAppPkgName != null
8790                        && isInstantApp
8791                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8792                    return null;
8793                }
8794                // instant application; filter out non-exposed provider
8795                if (instantAppPkgName != null
8796                        && !isInstantApp
8797                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8798                    return null;
8799                }
8800                // provider not enabled
8801                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8802                    return null;
8803                }
8804                return PackageParser.generateProviderInfo(
8805                        provider, flags, ps.readUserState(userId), userId);
8806            }
8807            return null;
8808        }
8809    }
8810
8811    /**
8812     * @deprecated
8813     */
8814    @Deprecated
8815    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8816        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8817            return;
8818        }
8819        // reader
8820        synchronized (mPackages) {
8821            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8822                    .entrySet().iterator();
8823            final int userId = UserHandle.getCallingUserId();
8824            while (i.hasNext()) {
8825                Map.Entry<String, PackageParser.Provider> entry = i.next();
8826                PackageParser.Provider p = entry.getValue();
8827                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8828
8829                if (ps != null && p.syncable
8830                        && (!mSafeMode || (p.info.applicationInfo.flags
8831                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8832                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8833                            ps.readUserState(userId), userId);
8834                    if (info != null) {
8835                        outNames.add(entry.getKey());
8836                        outInfo.add(info);
8837                    }
8838                }
8839            }
8840        }
8841    }
8842
8843    @Override
8844    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8845            int uid, int flags, String metaDataKey) {
8846        final int callingUid = Binder.getCallingUid();
8847        final int userId = processName != null ? UserHandle.getUserId(uid)
8848                : UserHandle.getCallingUserId();
8849        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8850        flags = updateFlagsForComponent(flags, userId, processName);
8851        ArrayList<ProviderInfo> finalList = null;
8852        // reader
8853        synchronized (mPackages) {
8854            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8855            while (i.hasNext()) {
8856                final PackageParser.Provider p = i.next();
8857                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8858                if (ps != null && p.info.authority != null
8859                        && (processName == null
8860                                || (p.info.processName.equals(processName)
8861                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8862                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8863
8864                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8865                    // parameter.
8866                    if (metaDataKey != null
8867                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8868                        continue;
8869                    }
8870                    final ComponentName component =
8871                            new ComponentName(p.info.packageName, p.info.name);
8872                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8873                        continue;
8874                    }
8875                    if (finalList == null) {
8876                        finalList = new ArrayList<ProviderInfo>(3);
8877                    }
8878                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8879                            ps.readUserState(userId), userId);
8880                    if (info != null) {
8881                        finalList.add(info);
8882                    }
8883                }
8884            }
8885        }
8886
8887        if (finalList != null) {
8888            Collections.sort(finalList, mProviderInitOrderSorter);
8889            return new ParceledListSlice<ProviderInfo>(finalList);
8890        }
8891
8892        return ParceledListSlice.emptyList();
8893    }
8894
8895    @Override
8896    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8897        // reader
8898        synchronized (mPackages) {
8899            final int callingUid = Binder.getCallingUid();
8900            final int callingUserId = UserHandle.getUserId(callingUid);
8901            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8902            if (ps == null) return null;
8903            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8904                return null;
8905            }
8906            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8907            return PackageParser.generateInstrumentationInfo(i, flags);
8908        }
8909    }
8910
8911    @Override
8912    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8913            String targetPackage, int flags) {
8914        final int callingUid = Binder.getCallingUid();
8915        final int callingUserId = UserHandle.getUserId(callingUid);
8916        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8917        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8918            return ParceledListSlice.emptyList();
8919        }
8920        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8921    }
8922
8923    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8924            int flags) {
8925        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8926
8927        // reader
8928        synchronized (mPackages) {
8929            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8930            while (i.hasNext()) {
8931                final PackageParser.Instrumentation p = i.next();
8932                if (targetPackage == null
8933                        || targetPackage.equals(p.info.targetPackage)) {
8934                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8935                            flags);
8936                    if (ii != null) {
8937                        finalList.add(ii);
8938                    }
8939                }
8940            }
8941        }
8942
8943        return finalList;
8944    }
8945
8946    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8947        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8948        try {
8949            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8950        } finally {
8951            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8952        }
8953    }
8954
8955    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8956        final File[] files = dir.listFiles();
8957        if (ArrayUtils.isEmpty(files)) {
8958            Log.d(TAG, "No files in app dir " + dir);
8959            return;
8960        }
8961
8962        if (DEBUG_PACKAGE_SCANNING) {
8963            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8964                    + " flags=0x" + Integer.toHexString(parseFlags));
8965        }
8966        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8967                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8968                mParallelPackageParserCallback);
8969
8970        // Submit files for parsing in parallel
8971        int fileCount = 0;
8972        for (File file : files) {
8973            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8974                    && !PackageInstallerService.isStageName(file.getName());
8975            if (!isPackage) {
8976                // Ignore entries which are not packages
8977                continue;
8978            }
8979            parallelPackageParser.submit(file, parseFlags);
8980            fileCount++;
8981        }
8982
8983        // Process results one by one
8984        for (; fileCount > 0; fileCount--) {
8985            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8986            Throwable throwable = parseResult.throwable;
8987            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8988
8989            if (throwable == null) {
8990                // Static shared libraries have synthetic package names
8991                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8992                    renameStaticSharedLibraryPackage(parseResult.pkg);
8993                }
8994                try {
8995                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8996                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8997                                currentTime, null);
8998                    }
8999                } catch (PackageManagerException e) {
9000                    errorCode = e.error;
9001                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
9002                }
9003            } else if (throwable instanceof PackageParser.PackageParserException) {
9004                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
9005                        throwable;
9006                errorCode = e.error;
9007                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
9008            } else {
9009                throw new IllegalStateException("Unexpected exception occurred while parsing "
9010                        + parseResult.scanFile, throwable);
9011            }
9012
9013            // Delete invalid userdata apps
9014            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
9015                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
9016                logCriticalInfo(Log.WARN,
9017                        "Deleting invalid package at " + parseResult.scanFile);
9018                removeCodePathLI(parseResult.scanFile);
9019            }
9020        }
9021        parallelPackageParser.close();
9022    }
9023
9024    private static File getSettingsProblemFile() {
9025        File dataDir = Environment.getDataDirectory();
9026        File systemDir = new File(dataDir, "system");
9027        File fname = new File(systemDir, "uiderrors.txt");
9028        return fname;
9029    }
9030
9031    static void reportSettingsProblem(int priority, String msg) {
9032        logCriticalInfo(priority, msg);
9033    }
9034
9035    public static void logCriticalInfo(int priority, String msg) {
9036        Slog.println(priority, TAG, msg);
9037        EventLogTags.writePmCriticalInfo(msg);
9038        try {
9039            File fname = getSettingsProblemFile();
9040            FileOutputStream out = new FileOutputStream(fname, true);
9041            PrintWriter pw = new FastPrintWriter(out);
9042            SimpleDateFormat formatter = new SimpleDateFormat();
9043            String dateString = formatter.format(new Date(System.currentTimeMillis()));
9044            pw.println(dateString + ": " + msg);
9045            pw.close();
9046            FileUtils.setPermissions(
9047                    fname.toString(),
9048                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
9049                    -1, -1);
9050        } catch (java.io.IOException e) {
9051        }
9052    }
9053
9054    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
9055        if (srcFile.isDirectory()) {
9056            final File baseFile = new File(pkg.baseCodePath);
9057            long maxModifiedTime = baseFile.lastModified();
9058            if (pkg.splitCodePaths != null) {
9059                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
9060                    final File splitFile = new File(pkg.splitCodePaths[i]);
9061                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
9062                }
9063            }
9064            return maxModifiedTime;
9065        }
9066        return srcFile.lastModified();
9067    }
9068
9069    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
9070            final int policyFlags) throws PackageManagerException {
9071        // When upgrading from pre-N MR1, verify the package time stamp using the package
9072        // directory and not the APK file.
9073        final long lastModifiedTime = mIsPreNMR1Upgrade
9074                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
9075        if (ps != null
9076                && ps.codePath.equals(srcFile)
9077                && ps.timeStamp == lastModifiedTime
9078                && !isCompatSignatureUpdateNeeded(pkg)
9079                && !isRecoverSignatureUpdateNeeded(pkg)) {
9080            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
9081            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9082            ArraySet<PublicKey> signingKs;
9083            synchronized (mPackages) {
9084                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
9085            }
9086            if (ps.signatures.mSignatures != null
9087                    && ps.signatures.mSignatures.length != 0
9088                    && signingKs != null) {
9089                // Optimization: reuse the existing cached certificates
9090                // if the package appears to be unchanged.
9091                pkg.mSignatures = ps.signatures.mSignatures;
9092                pkg.mSigningKeys = signingKs;
9093                return;
9094            }
9095
9096            Slog.w(TAG, "PackageSetting for " + ps.name
9097                    + " is missing signatures.  Collecting certs again to recover them.");
9098        } else {
9099            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
9100        }
9101
9102        try {
9103            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
9104            PackageParser.collectCertificates(pkg, policyFlags);
9105        } catch (PackageParserException e) {
9106            throw PackageManagerException.from(e);
9107        } finally {
9108            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9109        }
9110    }
9111
9112    /**
9113     *  Traces a package scan.
9114     *  @see #scanPackageLI(File, int, int, long, UserHandle)
9115     */
9116    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
9117            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
9118        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
9119        try {
9120            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
9121        } finally {
9122            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9123        }
9124    }
9125
9126    /**
9127     *  Scans a package and returns the newly parsed package.
9128     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
9129     */
9130    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
9131            long currentTime, UserHandle user) throws PackageManagerException {
9132        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
9133        PackageParser pp = new PackageParser();
9134        pp.setSeparateProcesses(mSeparateProcesses);
9135        pp.setOnlyCoreApps(mOnlyCore);
9136        pp.setDisplayMetrics(mMetrics);
9137        pp.setCallback(mPackageParserCallback);
9138
9139        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
9140            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
9141        }
9142
9143        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
9144        final PackageParser.Package pkg;
9145        try {
9146            pkg = pp.parsePackage(scanFile, parseFlags);
9147        } catch (PackageParserException e) {
9148            throw PackageManagerException.from(e);
9149        } finally {
9150            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9151        }
9152
9153        // Static shared libraries have synthetic package names
9154        if (pkg.applicationInfo.isStaticSharedLibrary()) {
9155            renameStaticSharedLibraryPackage(pkg);
9156        }
9157
9158        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
9159    }
9160
9161    /**
9162     *  Scans a package and returns the newly parsed package.
9163     *  @throws PackageManagerException on a parse error.
9164     */
9165    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
9166            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9167            throws PackageManagerException {
9168        // If the package has children and this is the first dive in the function
9169        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
9170        // packages (parent and children) would be successfully scanned before the
9171        // actual scan since scanning mutates internal state and we want to atomically
9172        // install the package and its children.
9173        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9174            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9175                scanFlags |= SCAN_CHECK_ONLY;
9176            }
9177        } else {
9178            scanFlags &= ~SCAN_CHECK_ONLY;
9179        }
9180
9181        // Scan the parent
9182        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
9183                scanFlags, currentTime, user);
9184
9185        // Scan the children
9186        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9187        for (int i = 0; i < childCount; i++) {
9188            PackageParser.Package childPackage = pkg.childPackages.get(i);
9189            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
9190                    currentTime, user);
9191        }
9192
9193
9194        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9195            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
9196        }
9197
9198        return scannedPkg;
9199    }
9200
9201    /**
9202     *  Scans a package and returns the newly parsed package.
9203     *  @throws PackageManagerException on a parse error.
9204     */
9205    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
9206            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9207            throws PackageManagerException {
9208        PackageSetting ps = null;
9209        PackageSetting updatedPkg;
9210        // reader
9211        synchronized (mPackages) {
9212            // Look to see if we already know about this package.
9213            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
9214            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
9215                // This package has been renamed to its original name.  Let's
9216                // use that.
9217                ps = mSettings.getPackageLPr(oldName);
9218            }
9219            // If there was no original package, see one for the real package name.
9220            if (ps == null) {
9221                ps = mSettings.getPackageLPr(pkg.packageName);
9222            }
9223            // Check to see if this package could be hiding/updating a system
9224            // package.  Must look for it either under the original or real
9225            // package name depending on our state.
9226            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
9227            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
9228
9229            // If this is a package we don't know about on the system partition, we
9230            // may need to remove disabled child packages on the system partition
9231            // or may need to not add child packages if the parent apk is updated
9232            // on the data partition and no longer defines this child package.
9233            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
9234                // If this is a parent package for an updated system app and this system
9235                // app got an OTA update which no longer defines some of the child packages
9236                // we have to prune them from the disabled system packages.
9237                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9238                if (disabledPs != null) {
9239                    final int scannedChildCount = (pkg.childPackages != null)
9240                            ? pkg.childPackages.size() : 0;
9241                    final int disabledChildCount = disabledPs.childPackageNames != null
9242                            ? disabledPs.childPackageNames.size() : 0;
9243                    for (int i = 0; i < disabledChildCount; i++) {
9244                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
9245                        boolean disabledPackageAvailable = false;
9246                        for (int j = 0; j < scannedChildCount; j++) {
9247                            PackageParser.Package childPkg = pkg.childPackages.get(j);
9248                            if (childPkg.packageName.equals(disabledChildPackageName)) {
9249                                disabledPackageAvailable = true;
9250                                break;
9251                            }
9252                         }
9253                         if (!disabledPackageAvailable) {
9254                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
9255                         }
9256                    }
9257                }
9258            }
9259        }
9260
9261        final boolean isUpdatedPkg = updatedPkg != null;
9262        final boolean isUpdatedSystemPkg = isUpdatedPkg
9263                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
9264        boolean isUpdatedPkgBetter = false;
9265        // First check if this is a system package that may involve an update
9266        if (isUpdatedSystemPkg) {
9267            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
9268            // it needs to drop FLAG_PRIVILEGED.
9269            if (locationIsPrivileged(scanFile)) {
9270                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9271            } else {
9272                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9273            }
9274
9275            if (ps != null && !ps.codePath.equals(scanFile)) {
9276                // The path has changed from what was last scanned...  check the
9277                // version of the new path against what we have stored to determine
9278                // what to do.
9279                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
9280                if (pkg.mVersionCode <= ps.versionCode) {
9281                    // The system package has been updated and the code path does not match
9282                    // Ignore entry. Skip it.
9283                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
9284                            + " ignored: updated version " + ps.versionCode
9285                            + " better than this " + pkg.mVersionCode);
9286                    if (!updatedPkg.codePath.equals(scanFile)) {
9287                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
9288                                + ps.name + " changing from " + updatedPkg.codePathString
9289                                + " to " + scanFile);
9290                        updatedPkg.codePath = scanFile;
9291                        updatedPkg.codePathString = scanFile.toString();
9292                        updatedPkg.resourcePath = scanFile;
9293                        updatedPkg.resourcePathString = scanFile.toString();
9294                    }
9295                    updatedPkg.pkg = pkg;
9296                    updatedPkg.versionCode = pkg.mVersionCode;
9297
9298                    // Update the disabled system child packages to point to the package too.
9299                    final int childCount = updatedPkg.childPackageNames != null
9300                            ? updatedPkg.childPackageNames.size() : 0;
9301                    for (int i = 0; i < childCount; i++) {
9302                        String childPackageName = updatedPkg.childPackageNames.get(i);
9303                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
9304                                childPackageName);
9305                        if (updatedChildPkg != null) {
9306                            updatedChildPkg.pkg = pkg;
9307                            updatedChildPkg.versionCode = pkg.mVersionCode;
9308                        }
9309                    }
9310                } else {
9311                    // The current app on the system partition is better than
9312                    // what we have updated to on the data partition; switch
9313                    // back to the system partition version.
9314                    // At this point, its safely assumed that package installation for
9315                    // apps in system partition will go through. If not there won't be a working
9316                    // version of the app
9317                    // writer
9318                    synchronized (mPackages) {
9319                        // Just remove the loaded entries from package lists.
9320                        mPackages.remove(ps.name);
9321                    }
9322
9323                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9324                            + " reverting from " + ps.codePathString
9325                            + ": new version " + pkg.mVersionCode
9326                            + " better than installed " + ps.versionCode);
9327
9328                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9329                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9330                    synchronized (mInstallLock) {
9331                        args.cleanUpResourcesLI();
9332                    }
9333                    synchronized (mPackages) {
9334                        mSettings.enableSystemPackageLPw(ps.name);
9335                    }
9336                    isUpdatedPkgBetter = true;
9337                }
9338            }
9339        }
9340
9341        String resourcePath = null;
9342        String baseResourcePath = null;
9343        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9344            if (ps != null && ps.resourcePathString != null) {
9345                resourcePath = ps.resourcePathString;
9346                baseResourcePath = ps.resourcePathString;
9347            } else {
9348                // Should not happen at all. Just log an error.
9349                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9350            }
9351        } else {
9352            resourcePath = pkg.codePath;
9353            baseResourcePath = pkg.baseCodePath;
9354        }
9355
9356        // Set application objects path explicitly.
9357        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9358        pkg.setApplicationInfoCodePath(pkg.codePath);
9359        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9360        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9361        pkg.setApplicationInfoResourcePath(resourcePath);
9362        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9363        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9364
9365        // throw an exception if we have an update to a system application, but, it's not more
9366        // recent than the package we've already scanned
9367        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9368            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9369                    + scanFile + " ignored: updated version " + ps.versionCode
9370                    + " better than this " + pkg.mVersionCode);
9371        }
9372
9373        if (isUpdatedPkg) {
9374            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9375            // initially
9376            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9377
9378            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9379            // flag set initially
9380            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9381                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9382            }
9383        }
9384
9385        // Verify certificates against what was last scanned
9386        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9387
9388        /*
9389         * A new system app appeared, but we already had a non-system one of the
9390         * same name installed earlier.
9391         */
9392        boolean shouldHideSystemApp = false;
9393        if (!isUpdatedPkg && ps != null
9394                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9395            /*
9396             * Check to make sure the signatures match first. If they don't,
9397             * wipe the installed application and its data.
9398             */
9399            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9400                    != PackageManager.SIGNATURE_MATCH) {
9401                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9402                        + " signatures don't match existing userdata copy; removing");
9403                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9404                        "scanPackageInternalLI")) {
9405                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9406                }
9407                ps = null;
9408            } else {
9409                /*
9410                 * If the newly-added system app is an older version than the
9411                 * already installed version, hide it. It will be scanned later
9412                 * and re-added like an update.
9413                 */
9414                if (pkg.mVersionCode <= ps.versionCode) {
9415                    shouldHideSystemApp = true;
9416                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9417                            + " but new version " + pkg.mVersionCode + " better than installed "
9418                            + ps.versionCode + "; hiding system");
9419                } else {
9420                    /*
9421                     * The newly found system app is a newer version that the
9422                     * one previously installed. Simply remove the
9423                     * already-installed application and replace it with our own
9424                     * while keeping the application data.
9425                     */
9426                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9427                            + " reverting from " + ps.codePathString + ": new version "
9428                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9429                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9430                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9431                    synchronized (mInstallLock) {
9432                        args.cleanUpResourcesLI();
9433                    }
9434                }
9435            }
9436        }
9437
9438        // The apk is forward locked (not public) if its code and resources
9439        // are kept in different files. (except for app in either system or
9440        // vendor path).
9441        // TODO grab this value from PackageSettings
9442        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9443            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9444                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9445            }
9446        }
9447
9448        final int userId = ((user == null) ? 0 : user.getIdentifier());
9449        if (ps != null && ps.getInstantApp(userId)) {
9450            scanFlags |= SCAN_AS_INSTANT_APP;
9451        }
9452        if (ps != null && ps.getVirtulalPreload(userId)) {
9453            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9454        }
9455
9456        // Note that we invoke the following method only if we are about to unpack an application
9457        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9458                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9459
9460        /*
9461         * If the system app should be overridden by a previously installed
9462         * data, hide the system app now and let the /data/app scan pick it up
9463         * again.
9464         */
9465        if (shouldHideSystemApp) {
9466            synchronized (mPackages) {
9467                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9468            }
9469        }
9470
9471        return scannedPkg;
9472    }
9473
9474    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9475        // Derive the new package synthetic package name
9476        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9477                + pkg.staticSharedLibVersion);
9478    }
9479
9480    private static String fixProcessName(String defProcessName,
9481            String processName) {
9482        if (processName == null) {
9483            return defProcessName;
9484        }
9485        return processName;
9486    }
9487
9488    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9489            throws PackageManagerException {
9490        if (pkgSetting.signatures.mSignatures != null) {
9491            // Already existing package. Make sure signatures match
9492            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9493                    == PackageManager.SIGNATURE_MATCH;
9494            if (!match) {
9495                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9496                        == PackageManager.SIGNATURE_MATCH;
9497            }
9498            if (!match) {
9499                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9500                        == PackageManager.SIGNATURE_MATCH;
9501            }
9502            if (!match) {
9503                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9504                        + pkg.packageName + " signatures do not match the "
9505                        + "previously installed version; ignoring!");
9506            }
9507        }
9508
9509        // Check for shared user signatures
9510        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9511            // Already existing package. Make sure signatures match
9512            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9513                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9514            if (!match) {
9515                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9516                        == PackageManager.SIGNATURE_MATCH;
9517            }
9518            if (!match) {
9519                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9520                        == PackageManager.SIGNATURE_MATCH;
9521            }
9522            if (!match) {
9523                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9524                        "Package " + pkg.packageName
9525                        + " has no signatures that match those in shared user "
9526                        + pkgSetting.sharedUser.name + "; ignoring!");
9527            }
9528        }
9529    }
9530
9531    /**
9532     * Enforces that only the system UID or root's UID can call a method exposed
9533     * via Binder.
9534     *
9535     * @param message used as message if SecurityException is thrown
9536     * @throws SecurityException if the caller is not system or root
9537     */
9538    private static final void enforceSystemOrRoot(String message) {
9539        final int uid = Binder.getCallingUid();
9540        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9541            throw new SecurityException(message);
9542        }
9543    }
9544
9545    @Override
9546    public void performFstrimIfNeeded() {
9547        enforceSystemOrRoot("Only the system can request fstrim");
9548
9549        // Before everything else, see whether we need to fstrim.
9550        try {
9551            IStorageManager sm = PackageHelper.getStorageManager();
9552            if (sm != null) {
9553                boolean doTrim = false;
9554                final long interval = android.provider.Settings.Global.getLong(
9555                        mContext.getContentResolver(),
9556                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9557                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9558                if (interval > 0) {
9559                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9560                    if (timeSinceLast > interval) {
9561                        doTrim = true;
9562                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9563                                + "; running immediately");
9564                    }
9565                }
9566                if (doTrim) {
9567                    final boolean dexOptDialogShown;
9568                    synchronized (mPackages) {
9569                        dexOptDialogShown = mDexOptDialogShown;
9570                    }
9571                    if (!isFirstBoot() && dexOptDialogShown) {
9572                        try {
9573                            ActivityManager.getService().showBootMessage(
9574                                    mContext.getResources().getString(
9575                                            R.string.android_upgrading_fstrim), true);
9576                        } catch (RemoteException e) {
9577                        }
9578                    }
9579                    sm.runMaintenance();
9580                }
9581            } else {
9582                Slog.e(TAG, "storageManager service unavailable!");
9583            }
9584        } catch (RemoteException e) {
9585            // Can't happen; StorageManagerService is local
9586        }
9587    }
9588
9589    @Override
9590    public void updatePackagesIfNeeded() {
9591        enforceSystemOrRoot("Only the system can request package update");
9592
9593        // We need to re-extract after an OTA.
9594        boolean causeUpgrade = isUpgrade();
9595
9596        // First boot or factory reset.
9597        // Note: we also handle devices that are upgrading to N right now as if it is their
9598        //       first boot, as they do not have profile data.
9599        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9600
9601        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9602        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9603
9604        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9605            return;
9606        }
9607
9608        List<PackageParser.Package> pkgs;
9609        synchronized (mPackages) {
9610            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9611        }
9612
9613        final long startTime = System.nanoTime();
9614        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9615                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9616                    false /* bootComplete */);
9617
9618        final int elapsedTimeSeconds =
9619                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9620
9621        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9622        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9623        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9624        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9625        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9626    }
9627
9628    /*
9629     * Return the prebuilt profile path given a package base code path.
9630     */
9631    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9632        return pkg.baseCodePath + ".prof";
9633    }
9634
9635    /**
9636     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9637     * containing statistics about the invocation. The array consists of three elements,
9638     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9639     * and {@code numberOfPackagesFailed}.
9640     */
9641    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9642            String compilerFilter, boolean bootComplete) {
9643
9644        int numberOfPackagesVisited = 0;
9645        int numberOfPackagesOptimized = 0;
9646        int numberOfPackagesSkipped = 0;
9647        int numberOfPackagesFailed = 0;
9648        final int numberOfPackagesToDexopt = pkgs.size();
9649
9650        for (PackageParser.Package pkg : pkgs) {
9651            numberOfPackagesVisited++;
9652
9653            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9654                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9655                // that are already compiled.
9656                File profileFile = new File(getPrebuildProfilePath(pkg));
9657                // Copy profile if it exists.
9658                if (profileFile.exists()) {
9659                    try {
9660                        // We could also do this lazily before calling dexopt in
9661                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9662                        // is that we don't have a good way to say "do this only once".
9663                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9664                                pkg.applicationInfo.uid, pkg.packageName)) {
9665                            Log.e(TAG, "Installer failed to copy system profile!");
9666                        }
9667                    } catch (Exception e) {
9668                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9669                                e);
9670                    }
9671                }
9672            }
9673
9674            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9675                if (DEBUG_DEXOPT) {
9676                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9677                }
9678                numberOfPackagesSkipped++;
9679                continue;
9680            }
9681
9682            if (DEBUG_DEXOPT) {
9683                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9684                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9685            }
9686
9687            if (showDialog) {
9688                try {
9689                    ActivityManager.getService().showBootMessage(
9690                            mContext.getResources().getString(R.string.android_upgrading_apk,
9691                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9692                } catch (RemoteException e) {
9693                }
9694                synchronized (mPackages) {
9695                    mDexOptDialogShown = true;
9696                }
9697            }
9698
9699            // If the OTA updates a system app which was previously preopted to a non-preopted state
9700            // the app might end up being verified at runtime. That's because by default the apps
9701            // are verify-profile but for preopted apps there's no profile.
9702            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9703            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9704            // filter (by default 'quicken').
9705            // Note that at this stage unused apps are already filtered.
9706            if (isSystemApp(pkg) &&
9707                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9708                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9709                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9710            }
9711
9712            // checkProfiles is false to avoid merging profiles during boot which
9713            // might interfere with background compilation (b/28612421).
9714            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9715            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9716            // trade-off worth doing to save boot time work.
9717            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9718            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9719                    pkg.packageName,
9720                    compilerFilter,
9721                    dexoptFlags));
9722
9723            if (pkg.isSystemApp()) {
9724                // Only dexopt shared secondary dex files belonging to system apps to not slow down
9725                // too much boot after an OTA.
9726                int secondaryDexoptFlags = dexoptFlags |
9727                        DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9728                        DexoptOptions.DEXOPT_ONLY_SHARED_DEX;
9729                mDexManager.dexoptSecondaryDex(new DexoptOptions(
9730                        pkg.packageName,
9731                        compilerFilter,
9732                        secondaryDexoptFlags));
9733            }
9734
9735            // TODO(shubhamajmera): Record secondary dexopt stats.
9736            switch (primaryDexOptStaus) {
9737                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9738                    numberOfPackagesOptimized++;
9739                    break;
9740                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9741                    numberOfPackagesSkipped++;
9742                    break;
9743                case PackageDexOptimizer.DEX_OPT_FAILED:
9744                    numberOfPackagesFailed++;
9745                    break;
9746                default:
9747                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9748                    break;
9749            }
9750        }
9751
9752        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9753                numberOfPackagesFailed };
9754    }
9755
9756    @Override
9757    public void notifyPackageUse(String packageName, int reason) {
9758        synchronized (mPackages) {
9759            final int callingUid = Binder.getCallingUid();
9760            final int callingUserId = UserHandle.getUserId(callingUid);
9761            if (getInstantAppPackageName(callingUid) != null) {
9762                if (!isCallerSameApp(packageName, callingUid)) {
9763                    return;
9764                }
9765            } else {
9766                if (isInstantApp(packageName, callingUserId)) {
9767                    return;
9768                }
9769            }
9770            final PackageParser.Package p = mPackages.get(packageName);
9771            if (p == null) {
9772                return;
9773            }
9774            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9775        }
9776    }
9777
9778    @Override
9779    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9780            List<String> classPaths, String loaderIsa) {
9781        int userId = UserHandle.getCallingUserId();
9782        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9783        if (ai == null) {
9784            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9785                + loadingPackageName + ", user=" + userId);
9786            return;
9787        }
9788        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9789    }
9790
9791    @Override
9792    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9793            IDexModuleRegisterCallback callback) {
9794        int userId = UserHandle.getCallingUserId();
9795        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9796        DexManager.RegisterDexModuleResult result;
9797        if (ai == null) {
9798            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9799                     " calling user. package=" + packageName + ", user=" + userId);
9800            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9801        } else {
9802            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9803        }
9804
9805        if (callback != null) {
9806            mHandler.post(() -> {
9807                try {
9808                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9809                } catch (RemoteException e) {
9810                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9811                }
9812            });
9813        }
9814    }
9815
9816    /**
9817     * Ask the package manager to perform a dex-opt with the given compiler filter.
9818     *
9819     * Note: exposed only for the shell command to allow moving packages explicitly to a
9820     *       definite state.
9821     */
9822    @Override
9823    public boolean performDexOptMode(String packageName,
9824            boolean checkProfiles, String targetCompilerFilter, boolean force,
9825            boolean bootComplete, String splitName) {
9826        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9827                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9828                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9829        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9830                splitName, flags));
9831    }
9832
9833    /**
9834     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9835     * secondary dex files belonging to the given package.
9836     *
9837     * Note: exposed only for the shell command to allow moving packages explicitly to a
9838     *       definite state.
9839     */
9840    @Override
9841    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9842            boolean force) {
9843        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9844                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9845                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9846                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9847        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9848    }
9849
9850    /*package*/ boolean performDexOpt(DexoptOptions options) {
9851        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9852            return false;
9853        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9854            return false;
9855        }
9856
9857        if (options.isDexoptOnlySecondaryDex()) {
9858            return mDexManager.dexoptSecondaryDex(options);
9859        } else {
9860            int dexoptStatus = performDexOptWithStatus(options);
9861            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9862        }
9863    }
9864
9865    /**
9866     * Perform dexopt on the given package and return one of following result:
9867     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9868     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9869     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9870     */
9871    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9872        return performDexOptTraced(options);
9873    }
9874
9875    private int performDexOptTraced(DexoptOptions options) {
9876        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9877        try {
9878            return performDexOptInternal(options);
9879        } finally {
9880            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9881        }
9882    }
9883
9884    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9885    // if the package can now be considered up to date for the given filter.
9886    private int performDexOptInternal(DexoptOptions options) {
9887        PackageParser.Package p;
9888        synchronized (mPackages) {
9889            p = mPackages.get(options.getPackageName());
9890            if (p == null) {
9891                // Package could not be found. Report failure.
9892                return PackageDexOptimizer.DEX_OPT_FAILED;
9893            }
9894            mPackageUsage.maybeWriteAsync(mPackages);
9895            mCompilerStats.maybeWriteAsync();
9896        }
9897        long callingId = Binder.clearCallingIdentity();
9898        try {
9899            synchronized (mInstallLock) {
9900                return performDexOptInternalWithDependenciesLI(p, options);
9901            }
9902        } finally {
9903            Binder.restoreCallingIdentity(callingId);
9904        }
9905    }
9906
9907    public ArraySet<String> getOptimizablePackages() {
9908        ArraySet<String> pkgs = new ArraySet<String>();
9909        synchronized (mPackages) {
9910            for (PackageParser.Package p : mPackages.values()) {
9911                if (PackageDexOptimizer.canOptimizePackage(p)) {
9912                    pkgs.add(p.packageName);
9913                }
9914            }
9915        }
9916        return pkgs;
9917    }
9918
9919    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9920            DexoptOptions options) {
9921        // Select the dex optimizer based on the force parameter.
9922        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9923        //       allocate an object here.
9924        PackageDexOptimizer pdo = options.isForce()
9925                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9926                : mPackageDexOptimizer;
9927
9928        // Dexopt all dependencies first. Note: we ignore the return value and march on
9929        // on errors.
9930        // Note that we are going to call performDexOpt on those libraries as many times as
9931        // they are referenced in packages. When we do a batch of performDexOpt (for example
9932        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9933        // and the first package that uses the library will dexopt it. The
9934        // others will see that the compiled code for the library is up to date.
9935        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9936        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9937        if (!deps.isEmpty()) {
9938            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9939                    options.getCompilerFilter(), options.getSplitName(),
9940                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9941            for (PackageParser.Package depPackage : deps) {
9942                // TODO: Analyze and investigate if we (should) profile libraries.
9943                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9944                        getOrCreateCompilerPackageStats(depPackage),
9945                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9946            }
9947        }
9948        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9949                getOrCreateCompilerPackageStats(p),
9950                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9951    }
9952
9953    /**
9954     * Reconcile the information we have about the secondary dex files belonging to
9955     * {@code packagName} and the actual dex files. For all dex files that were
9956     * deleted, update the internal records and delete the generated oat files.
9957     */
9958    @Override
9959    public void reconcileSecondaryDexFiles(String packageName) {
9960        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9961            return;
9962        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9963            return;
9964        }
9965        mDexManager.reconcileSecondaryDexFiles(packageName);
9966    }
9967
9968    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9969    // a reference there.
9970    /*package*/ DexManager getDexManager() {
9971        return mDexManager;
9972    }
9973
9974    /**
9975     * Execute the background dexopt job immediately.
9976     */
9977    @Override
9978    public boolean runBackgroundDexoptJob() {
9979        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9980            return false;
9981        }
9982        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9983    }
9984
9985    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9986        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9987                || p.usesStaticLibraries != null) {
9988            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9989            Set<String> collectedNames = new HashSet<>();
9990            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9991
9992            retValue.remove(p);
9993
9994            return retValue;
9995        } else {
9996            return Collections.emptyList();
9997        }
9998    }
9999
10000    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
10001            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10002        if (!collectedNames.contains(p.packageName)) {
10003            collectedNames.add(p.packageName);
10004            collected.add(p);
10005
10006            if (p.usesLibraries != null) {
10007                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
10008                        null, collected, collectedNames);
10009            }
10010            if (p.usesOptionalLibraries != null) {
10011                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
10012                        null, collected, collectedNames);
10013            }
10014            if (p.usesStaticLibraries != null) {
10015                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
10016                        p.usesStaticLibrariesVersions, collected, collectedNames);
10017            }
10018        }
10019    }
10020
10021    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
10022            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
10023        final int libNameCount = libs.size();
10024        for (int i = 0; i < libNameCount; i++) {
10025            String libName = libs.get(i);
10026            int version = (versions != null && versions.length == libNameCount)
10027                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
10028            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
10029            if (libPkg != null) {
10030                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
10031            }
10032        }
10033    }
10034
10035    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
10036        synchronized (mPackages) {
10037            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
10038            if (libEntry != null) {
10039                return mPackages.get(libEntry.apk);
10040            }
10041            return null;
10042        }
10043    }
10044
10045    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
10046        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10047        if (versionedLib == null) {
10048            return null;
10049        }
10050        return versionedLib.get(version);
10051    }
10052
10053    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
10054        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10055                pkg.staticSharedLibName);
10056        if (versionedLib == null) {
10057            return null;
10058        }
10059        int previousLibVersion = -1;
10060        final int versionCount = versionedLib.size();
10061        for (int i = 0; i < versionCount; i++) {
10062            final int libVersion = versionedLib.keyAt(i);
10063            if (libVersion < pkg.staticSharedLibVersion) {
10064                previousLibVersion = Math.max(previousLibVersion, libVersion);
10065            }
10066        }
10067        if (previousLibVersion >= 0) {
10068            return versionedLib.get(previousLibVersion);
10069        }
10070        return null;
10071    }
10072
10073    public void shutdown() {
10074        mPackageUsage.writeNow(mPackages);
10075        mCompilerStats.writeNow();
10076        mDexManager.writePackageDexUsageNow();
10077    }
10078
10079    @Override
10080    public void dumpProfiles(String packageName) {
10081        PackageParser.Package pkg;
10082        synchronized (mPackages) {
10083            pkg = mPackages.get(packageName);
10084            if (pkg == null) {
10085                throw new IllegalArgumentException("Unknown package: " + packageName);
10086            }
10087        }
10088        /* Only the shell, root, or the app user should be able to dump profiles. */
10089        int callingUid = Binder.getCallingUid();
10090        if (callingUid != Process.SHELL_UID &&
10091            callingUid != Process.ROOT_UID &&
10092            callingUid != pkg.applicationInfo.uid) {
10093            throw new SecurityException("dumpProfiles");
10094        }
10095
10096        synchronized (mInstallLock) {
10097            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
10098            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
10099            try {
10100                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
10101                String codePaths = TextUtils.join(";", allCodePaths);
10102                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
10103            } catch (InstallerException e) {
10104                Slog.w(TAG, "Failed to dump profiles", e);
10105            }
10106            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10107        }
10108    }
10109
10110    @Override
10111    public void forceDexOpt(String packageName) {
10112        enforceSystemOrRoot("forceDexOpt");
10113
10114        PackageParser.Package pkg;
10115        synchronized (mPackages) {
10116            pkg = mPackages.get(packageName);
10117            if (pkg == null) {
10118                throw new IllegalArgumentException("Unknown package: " + packageName);
10119            }
10120        }
10121
10122        synchronized (mInstallLock) {
10123            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
10124
10125            // Whoever is calling forceDexOpt wants a compiled package.
10126            // Don't use profiles since that may cause compilation to be skipped.
10127            final int res = performDexOptInternalWithDependenciesLI(
10128                    pkg,
10129                    new DexoptOptions(packageName,
10130                            getDefaultCompilerFilter(),
10131                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
10132
10133            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10134            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
10135                throw new IllegalStateException("Failed to dexopt: " + res);
10136            }
10137        }
10138    }
10139
10140    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
10141        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
10142            Slog.w(TAG, "Unable to update from " + oldPkg.name
10143                    + " to " + newPkg.packageName
10144                    + ": old package not in system partition");
10145            return false;
10146        } else if (mPackages.get(oldPkg.name) != null) {
10147            Slog.w(TAG, "Unable to update from " + oldPkg.name
10148                    + " to " + newPkg.packageName
10149                    + ": old package still exists");
10150            return false;
10151        }
10152        return true;
10153    }
10154
10155    void removeCodePathLI(File codePath) {
10156        if (codePath.isDirectory()) {
10157            try {
10158                mInstaller.rmPackageDir(codePath.getAbsolutePath());
10159            } catch (InstallerException e) {
10160                Slog.w(TAG, "Failed to remove code path", e);
10161            }
10162        } else {
10163            codePath.delete();
10164        }
10165    }
10166
10167    private int[] resolveUserIds(int userId) {
10168        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
10169    }
10170
10171    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10172        if (pkg == null) {
10173            Slog.wtf(TAG, "Package was null!", new Throwable());
10174            return;
10175        }
10176        clearAppDataLeafLIF(pkg, userId, flags);
10177        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10178        for (int i = 0; i < childCount; i++) {
10179            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10180        }
10181    }
10182
10183    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10184        final PackageSetting ps;
10185        synchronized (mPackages) {
10186            ps = mSettings.mPackages.get(pkg.packageName);
10187        }
10188        for (int realUserId : resolveUserIds(userId)) {
10189            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10190            try {
10191                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10192                        ceDataInode);
10193            } catch (InstallerException e) {
10194                Slog.w(TAG, String.valueOf(e));
10195            }
10196        }
10197    }
10198
10199    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10200        if (pkg == null) {
10201            Slog.wtf(TAG, "Package was null!", new Throwable());
10202            return;
10203        }
10204        destroyAppDataLeafLIF(pkg, userId, flags);
10205        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10206        for (int i = 0; i < childCount; i++) {
10207            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10208        }
10209    }
10210
10211    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10212        final PackageSetting ps;
10213        synchronized (mPackages) {
10214            ps = mSettings.mPackages.get(pkg.packageName);
10215        }
10216        for (int realUserId : resolveUserIds(userId)) {
10217            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10218            try {
10219                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10220                        ceDataInode);
10221            } catch (InstallerException e) {
10222                Slog.w(TAG, String.valueOf(e));
10223            }
10224            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
10225        }
10226    }
10227
10228    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
10229        if (pkg == null) {
10230            Slog.wtf(TAG, "Package was null!", new Throwable());
10231            return;
10232        }
10233        destroyAppProfilesLeafLIF(pkg);
10234        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10235        for (int i = 0; i < childCount; i++) {
10236            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
10237        }
10238    }
10239
10240    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
10241        try {
10242            mInstaller.destroyAppProfiles(pkg.packageName);
10243        } catch (InstallerException e) {
10244            Slog.w(TAG, String.valueOf(e));
10245        }
10246    }
10247
10248    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
10249        if (pkg == null) {
10250            Slog.wtf(TAG, "Package was null!", new Throwable());
10251            return;
10252        }
10253        clearAppProfilesLeafLIF(pkg);
10254        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10255        for (int i = 0; i < childCount; i++) {
10256            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
10257        }
10258    }
10259
10260    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
10261        try {
10262            mInstaller.clearAppProfiles(pkg.packageName);
10263        } catch (InstallerException e) {
10264            Slog.w(TAG, String.valueOf(e));
10265        }
10266    }
10267
10268    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
10269            long lastUpdateTime) {
10270        // Set parent install/update time
10271        PackageSetting ps = (PackageSetting) pkg.mExtras;
10272        if (ps != null) {
10273            ps.firstInstallTime = firstInstallTime;
10274            ps.lastUpdateTime = lastUpdateTime;
10275        }
10276        // Set children install/update time
10277        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10278        for (int i = 0; i < childCount; i++) {
10279            PackageParser.Package childPkg = pkg.childPackages.get(i);
10280            ps = (PackageSetting) childPkg.mExtras;
10281            if (ps != null) {
10282                ps.firstInstallTime = firstInstallTime;
10283                ps.lastUpdateTime = lastUpdateTime;
10284            }
10285        }
10286    }
10287
10288    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
10289            PackageParser.Package changingLib) {
10290        if (file.path != null) {
10291            usesLibraryFiles.add(file.path);
10292            return;
10293        }
10294        PackageParser.Package p = mPackages.get(file.apk);
10295        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
10296            // If we are doing this while in the middle of updating a library apk,
10297            // then we need to make sure to use that new apk for determining the
10298            // dependencies here.  (We haven't yet finished committing the new apk
10299            // to the package manager state.)
10300            if (p == null || p.packageName.equals(changingLib.packageName)) {
10301                p = changingLib;
10302            }
10303        }
10304        if (p != null) {
10305            usesLibraryFiles.addAll(p.getAllCodePaths());
10306            if (p.usesLibraryFiles != null) {
10307                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
10308            }
10309        }
10310    }
10311
10312    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
10313            PackageParser.Package changingLib) throws PackageManagerException {
10314        if (pkg == null) {
10315            return;
10316        }
10317        ArraySet<String> usesLibraryFiles = null;
10318        if (pkg.usesLibraries != null) {
10319            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
10320                    null, null, pkg.packageName, changingLib, true, null);
10321        }
10322        if (pkg.usesStaticLibraries != null) {
10323            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
10324                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
10325                    pkg.packageName, changingLib, true, usesLibraryFiles);
10326        }
10327        if (pkg.usesOptionalLibraries != null) {
10328            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
10329                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
10330        }
10331        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
10332            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10333        } else {
10334            pkg.usesLibraryFiles = null;
10335        }
10336    }
10337
10338    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10339            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
10340            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10341            boolean required, @Nullable ArraySet<String> outUsedLibraries)
10342            throws PackageManagerException {
10343        final int libCount = requestedLibraries.size();
10344        for (int i = 0; i < libCount; i++) {
10345            final String libName = requestedLibraries.get(i);
10346            final int libVersion = requiredVersions != null ? requiredVersions[i]
10347                    : SharedLibraryInfo.VERSION_UNDEFINED;
10348            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10349            if (libEntry == null) {
10350                if (required) {
10351                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10352                            "Package " + packageName + " requires unavailable shared library "
10353                                    + libName + "; failing!");
10354                } else if (DEBUG_SHARED_LIBRARIES) {
10355                    Slog.i(TAG, "Package " + packageName
10356                            + " desires unavailable shared library "
10357                            + libName + "; ignoring!");
10358                }
10359            } else {
10360                if (requiredVersions != null && requiredCertDigests != null) {
10361                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10362                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10363                            "Package " + packageName + " requires unavailable static shared"
10364                                    + " library " + libName + " version "
10365                                    + libEntry.info.getVersion() + "; failing!");
10366                    }
10367
10368                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10369                    if (libPkg == null) {
10370                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10371                                "Package " + packageName + " requires unavailable static shared"
10372                                        + " library; failing!");
10373                    }
10374
10375                    String expectedCertDigest = requiredCertDigests[i];
10376                    String libCertDigest = PackageUtils.computeCertSha256Digest(
10377                                libPkg.mSignatures[0]);
10378                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
10379                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10380                                "Package " + packageName + " requires differently signed" +
10381                                        " static shared library; failing!");
10382                    }
10383                }
10384
10385                if (outUsedLibraries == null) {
10386                    outUsedLibraries = new ArraySet<>();
10387                }
10388                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10389            }
10390        }
10391        return outUsedLibraries;
10392    }
10393
10394    private static boolean hasString(List<String> list, List<String> which) {
10395        if (list == null) {
10396            return false;
10397        }
10398        for (int i=list.size()-1; i>=0; i--) {
10399            for (int j=which.size()-1; j>=0; j--) {
10400                if (which.get(j).equals(list.get(i))) {
10401                    return true;
10402                }
10403            }
10404        }
10405        return false;
10406    }
10407
10408    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10409            PackageParser.Package changingPkg) {
10410        ArrayList<PackageParser.Package> res = null;
10411        for (PackageParser.Package pkg : mPackages.values()) {
10412            if (changingPkg != null
10413                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10414                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10415                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10416                            changingPkg.staticSharedLibName)) {
10417                return null;
10418            }
10419            if (res == null) {
10420                res = new ArrayList<>();
10421            }
10422            res.add(pkg);
10423            try {
10424                updateSharedLibrariesLPr(pkg, changingPkg);
10425            } catch (PackageManagerException e) {
10426                // If a system app update or an app and a required lib missing we
10427                // delete the package and for updated system apps keep the data as
10428                // it is better for the user to reinstall than to be in an limbo
10429                // state. Also libs disappearing under an app should never happen
10430                // - just in case.
10431                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10432                    final int flags = pkg.isUpdatedSystemApp()
10433                            ? PackageManager.DELETE_KEEP_DATA : 0;
10434                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10435                            flags , null, true, null);
10436                }
10437                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10438            }
10439        }
10440        return res;
10441    }
10442
10443    /**
10444     * Derive the value of the {@code cpuAbiOverride} based on the provided
10445     * value and an optional stored value from the package settings.
10446     */
10447    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10448        String cpuAbiOverride = null;
10449
10450        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10451            cpuAbiOverride = null;
10452        } else if (abiOverride != null) {
10453            cpuAbiOverride = abiOverride;
10454        } else if (settings != null) {
10455            cpuAbiOverride = settings.cpuAbiOverrideString;
10456        }
10457
10458        return cpuAbiOverride;
10459    }
10460
10461    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10462            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10463                    throws PackageManagerException {
10464        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10465        // If the package has children and this is the first dive in the function
10466        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10467        // whether all packages (parent and children) would be successfully scanned
10468        // before the actual scan since scanning mutates internal state and we want
10469        // to atomically install the package and its children.
10470        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10471            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10472                scanFlags |= SCAN_CHECK_ONLY;
10473            }
10474        } else {
10475            scanFlags &= ~SCAN_CHECK_ONLY;
10476        }
10477
10478        final PackageParser.Package scannedPkg;
10479        try {
10480            // Scan the parent
10481            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10482            // Scan the children
10483            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10484            for (int i = 0; i < childCount; i++) {
10485                PackageParser.Package childPkg = pkg.childPackages.get(i);
10486                scanPackageLI(childPkg, policyFlags,
10487                        scanFlags, currentTime, user);
10488            }
10489        } finally {
10490            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10491        }
10492
10493        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10494            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10495        }
10496
10497        return scannedPkg;
10498    }
10499
10500    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10501            int scanFlags, long currentTime, @Nullable UserHandle user)
10502                    throws PackageManagerException {
10503        boolean success = false;
10504        try {
10505            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10506                    currentTime, user);
10507            success = true;
10508            return res;
10509        } finally {
10510            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10511                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10512                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10513                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10514                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10515            }
10516        }
10517    }
10518
10519    /**
10520     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10521     */
10522    private static boolean apkHasCode(String fileName) {
10523        StrictJarFile jarFile = null;
10524        try {
10525            jarFile = new StrictJarFile(fileName,
10526                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10527            return jarFile.findEntry("classes.dex") != null;
10528        } catch (IOException ignore) {
10529        } finally {
10530            try {
10531                if (jarFile != null) {
10532                    jarFile.close();
10533                }
10534            } catch (IOException ignore) {}
10535        }
10536        return false;
10537    }
10538
10539    /**
10540     * Enforces code policy for the package. This ensures that if an APK has
10541     * declared hasCode="true" in its manifest that the APK actually contains
10542     * code.
10543     *
10544     * @throws PackageManagerException If bytecode could not be found when it should exist
10545     */
10546    private static void assertCodePolicy(PackageParser.Package pkg)
10547            throws PackageManagerException {
10548        final boolean shouldHaveCode =
10549                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10550        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10551            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10552                    "Package " + pkg.baseCodePath + " code is missing");
10553        }
10554
10555        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10556            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10557                final boolean splitShouldHaveCode =
10558                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10559                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10560                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10561                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10562                }
10563            }
10564        }
10565    }
10566
10567    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10568            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10569                    throws PackageManagerException {
10570        if (DEBUG_PACKAGE_SCANNING) {
10571            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10572                Log.d(TAG, "Scanning package " + pkg.packageName);
10573        }
10574
10575        applyPolicy(pkg, policyFlags);
10576
10577        assertPackageIsValid(pkg, policyFlags, scanFlags);
10578
10579        // Initialize package source and resource directories
10580        final File scanFile = new File(pkg.codePath);
10581        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10582        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10583
10584        SharedUserSetting suid = null;
10585        PackageSetting pkgSetting = null;
10586
10587        // Getting the package setting may have a side-effect, so if we
10588        // are only checking if scan would succeed, stash a copy of the
10589        // old setting to restore at the end.
10590        PackageSetting nonMutatedPs = null;
10591
10592        // We keep references to the derived CPU Abis from settings in oder to reuse
10593        // them in the case where we're not upgrading or booting for the first time.
10594        String primaryCpuAbiFromSettings = null;
10595        String secondaryCpuAbiFromSettings = null;
10596
10597        // writer
10598        synchronized (mPackages) {
10599            if (pkg.mSharedUserId != null) {
10600                // SIDE EFFECTS; may potentially allocate a new shared user
10601                suid = mSettings.getSharedUserLPw(
10602                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10603                if (DEBUG_PACKAGE_SCANNING) {
10604                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10605                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10606                                + "): packages=" + suid.packages);
10607                }
10608            }
10609
10610            // Check if we are renaming from an original package name.
10611            PackageSetting origPackage = null;
10612            String realName = null;
10613            if (pkg.mOriginalPackages != null) {
10614                // This package may need to be renamed to a previously
10615                // installed name.  Let's check on that...
10616                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10617                if (pkg.mOriginalPackages.contains(renamed)) {
10618                    // This package had originally been installed as the
10619                    // original name, and we have already taken care of
10620                    // transitioning to the new one.  Just update the new
10621                    // one to continue using the old name.
10622                    realName = pkg.mRealPackage;
10623                    if (!pkg.packageName.equals(renamed)) {
10624                        // Callers into this function may have already taken
10625                        // care of renaming the package; only do it here if
10626                        // it is not already done.
10627                        pkg.setPackageName(renamed);
10628                    }
10629                } else {
10630                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10631                        if ((origPackage = mSettings.getPackageLPr(
10632                                pkg.mOriginalPackages.get(i))) != null) {
10633                            // We do have the package already installed under its
10634                            // original name...  should we use it?
10635                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10636                                // New package is not compatible with original.
10637                                origPackage = null;
10638                                continue;
10639                            } else if (origPackage.sharedUser != null) {
10640                                // Make sure uid is compatible between packages.
10641                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10642                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10643                                            + " to " + pkg.packageName + ": old uid "
10644                                            + origPackage.sharedUser.name
10645                                            + " differs from " + pkg.mSharedUserId);
10646                                    origPackage = null;
10647                                    continue;
10648                                }
10649                                // TODO: Add case when shared user id is added [b/28144775]
10650                            } else {
10651                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10652                                        + pkg.packageName + " to old name " + origPackage.name);
10653                            }
10654                            break;
10655                        }
10656                    }
10657                }
10658            }
10659
10660            if (mTransferedPackages.contains(pkg.packageName)) {
10661                Slog.w(TAG, "Package " + pkg.packageName
10662                        + " was transferred to another, but its .apk remains");
10663            }
10664
10665            // See comments in nonMutatedPs declaration
10666            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10667                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10668                if (foundPs != null) {
10669                    nonMutatedPs = new PackageSetting(foundPs);
10670                }
10671            }
10672
10673            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10674                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10675                if (foundPs != null) {
10676                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10677                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10678                }
10679            }
10680
10681            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10682            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10683                PackageManagerService.reportSettingsProblem(Log.WARN,
10684                        "Package " + pkg.packageName + " shared user changed from "
10685                                + (pkgSetting.sharedUser != null
10686                                        ? pkgSetting.sharedUser.name : "<nothing>")
10687                                + " to "
10688                                + (suid != null ? suid.name : "<nothing>")
10689                                + "; replacing with new");
10690                pkgSetting = null;
10691            }
10692            final PackageSetting oldPkgSetting =
10693                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10694            final PackageSetting disabledPkgSetting =
10695                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10696
10697            String[] usesStaticLibraries = null;
10698            if (pkg.usesStaticLibraries != null) {
10699                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10700                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10701            }
10702
10703            if (pkgSetting == null) {
10704                final String parentPackageName = (pkg.parentPackage != null)
10705                        ? pkg.parentPackage.packageName : null;
10706                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10707                final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10708                // REMOVE SharedUserSetting from method; update in a separate call
10709                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10710                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10711                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10712                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10713                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10714                        true /*allowInstall*/, instantApp, virtualPreload,
10715                        parentPackageName, pkg.getChildPackageNames(),
10716                        UserManagerService.getInstance(), usesStaticLibraries,
10717                        pkg.usesStaticLibrariesVersions);
10718                // SIDE EFFECTS; updates system state; move elsewhere
10719                if (origPackage != null) {
10720                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10721                }
10722                mSettings.addUserToSettingLPw(pkgSetting);
10723            } else {
10724                // REMOVE SharedUserSetting from method; update in a separate call.
10725                //
10726                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10727                // secondaryCpuAbi are not known at this point so we always update them
10728                // to null here, only to reset them at a later point.
10729                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10730                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10731                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10732                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10733                        UserManagerService.getInstance(), usesStaticLibraries,
10734                        pkg.usesStaticLibrariesVersions);
10735            }
10736            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10737            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10738
10739            // SIDE EFFECTS; modifies system state; move elsewhere
10740            if (pkgSetting.origPackage != null) {
10741                // If we are first transitioning from an original package,
10742                // fix up the new package's name now.  We need to do this after
10743                // looking up the package under its new name, so getPackageLP
10744                // can take care of fiddling things correctly.
10745                pkg.setPackageName(origPackage.name);
10746
10747                // File a report about this.
10748                String msg = "New package " + pkgSetting.realName
10749                        + " renamed to replace old package " + pkgSetting.name;
10750                reportSettingsProblem(Log.WARN, msg);
10751
10752                // Make a note of it.
10753                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10754                    mTransferedPackages.add(origPackage.name);
10755                }
10756
10757                // No longer need to retain this.
10758                pkgSetting.origPackage = null;
10759            }
10760
10761            // SIDE EFFECTS; modifies system state; move elsewhere
10762            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10763                // Make a note of it.
10764                mTransferedPackages.add(pkg.packageName);
10765            }
10766
10767            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10768                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10769            }
10770
10771            if ((scanFlags & SCAN_BOOTING) == 0
10772                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10773                // Check all shared libraries and map to their actual file path.
10774                // We only do this here for apps not on a system dir, because those
10775                // are the only ones that can fail an install due to this.  We
10776                // will take care of the system apps by updating all of their
10777                // library paths after the scan is done. Also during the initial
10778                // scan don't update any libs as we do this wholesale after all
10779                // apps are scanned to avoid dependency based scanning.
10780                updateSharedLibrariesLPr(pkg, null);
10781            }
10782
10783            if (mFoundPolicyFile) {
10784                SELinuxMMAC.assignSeInfoValue(pkg);
10785            }
10786            pkg.applicationInfo.uid = pkgSetting.appId;
10787            pkg.mExtras = pkgSetting;
10788
10789
10790            // Static shared libs have same package with different versions where
10791            // we internally use a synthetic package name to allow multiple versions
10792            // of the same package, therefore we need to compare signatures against
10793            // the package setting for the latest library version.
10794            PackageSetting signatureCheckPs = pkgSetting;
10795            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10796                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10797                if (libraryEntry != null) {
10798                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10799                }
10800            }
10801
10802            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10803                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10804                    // We just determined the app is signed correctly, so bring
10805                    // over the latest parsed certs.
10806                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10807                } else {
10808                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10809                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10810                                "Package " + pkg.packageName + " upgrade keys do not match the "
10811                                + "previously installed version");
10812                    } else {
10813                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10814                        String msg = "System package " + pkg.packageName
10815                                + " signature changed; retaining data.";
10816                        reportSettingsProblem(Log.WARN, msg);
10817                    }
10818                }
10819            } else {
10820                try {
10821                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10822                    verifySignaturesLP(signatureCheckPs, pkg);
10823                    // We just determined the app is signed correctly, so bring
10824                    // over the latest parsed certs.
10825                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10826                } catch (PackageManagerException e) {
10827                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10828                        throw e;
10829                    }
10830                    // The signature has changed, but this package is in the system
10831                    // image...  let's recover!
10832                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10833                    // However...  if this package is part of a shared user, but it
10834                    // doesn't match the signature of the shared user, let's fail.
10835                    // What this means is that you can't change the signatures
10836                    // associated with an overall shared user, which doesn't seem all
10837                    // that unreasonable.
10838                    if (signatureCheckPs.sharedUser != null) {
10839                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10840                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10841                            throw new PackageManagerException(
10842                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10843                                    "Signature mismatch for shared user: "
10844                                            + pkgSetting.sharedUser);
10845                        }
10846                    }
10847                    // File a report about this.
10848                    String msg = "System package " + pkg.packageName
10849                            + " signature changed; retaining data.";
10850                    reportSettingsProblem(Log.WARN, msg);
10851                }
10852            }
10853
10854            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10855                // This package wants to adopt ownership of permissions from
10856                // another package.
10857                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10858                    final String origName = pkg.mAdoptPermissions.get(i);
10859                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10860                    if (orig != null) {
10861                        if (verifyPackageUpdateLPr(orig, pkg)) {
10862                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10863                                    + pkg.packageName);
10864                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10865                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10866                        }
10867                    }
10868                }
10869            }
10870        }
10871
10872        pkg.applicationInfo.processName = fixProcessName(
10873                pkg.applicationInfo.packageName,
10874                pkg.applicationInfo.processName);
10875
10876        if (pkg != mPlatformPackage) {
10877            // Get all of our default paths setup
10878            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10879        }
10880
10881        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10882
10883        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10884            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10885                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10886                final boolean extractNativeLibs = !pkg.isLibrary();
10887                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10888                        mAppLib32InstallDir);
10889                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10890
10891                // Some system apps still use directory structure for native libraries
10892                // in which case we might end up not detecting abi solely based on apk
10893                // structure. Try to detect abi based on directory structure.
10894                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10895                        pkg.applicationInfo.primaryCpuAbi == null) {
10896                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10897                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10898                }
10899            } else {
10900                // This is not a first boot or an upgrade, don't bother deriving the
10901                // ABI during the scan. Instead, trust the value that was stored in the
10902                // package setting.
10903                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10904                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10905
10906                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10907
10908                if (DEBUG_ABI_SELECTION) {
10909                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10910                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10911                        pkg.applicationInfo.secondaryCpuAbi);
10912                }
10913            }
10914        } else {
10915            if ((scanFlags & SCAN_MOVE) != 0) {
10916                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10917                // but we already have this packages package info in the PackageSetting. We just
10918                // use that and derive the native library path based on the new codepath.
10919                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10920                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10921            }
10922
10923            // Set native library paths again. For moves, the path will be updated based on the
10924            // ABIs we've determined above. For non-moves, the path will be updated based on the
10925            // ABIs we determined during compilation, but the path will depend on the final
10926            // package path (after the rename away from the stage path).
10927            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10928        }
10929
10930        // This is a special case for the "system" package, where the ABI is
10931        // dictated by the zygote configuration (and init.rc). We should keep track
10932        // of this ABI so that we can deal with "normal" applications that run under
10933        // the same UID correctly.
10934        if (mPlatformPackage == pkg) {
10935            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10936                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10937        }
10938
10939        // If there's a mismatch between the abi-override in the package setting
10940        // and the abiOverride specified for the install. Warn about this because we
10941        // would've already compiled the app without taking the package setting into
10942        // account.
10943        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10944            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10945                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10946                        " for package " + pkg.packageName);
10947            }
10948        }
10949
10950        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10951        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10952        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10953
10954        // Copy the derived override back to the parsed package, so that we can
10955        // update the package settings accordingly.
10956        pkg.cpuAbiOverride = cpuAbiOverride;
10957
10958        if (DEBUG_ABI_SELECTION) {
10959            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10960                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10961                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10962        }
10963
10964        // Push the derived path down into PackageSettings so we know what to
10965        // clean up at uninstall time.
10966        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10967
10968        if (DEBUG_ABI_SELECTION) {
10969            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10970                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10971                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10972        }
10973
10974        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10975        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10976            // We don't do this here during boot because we can do it all
10977            // at once after scanning all existing packages.
10978            //
10979            // We also do this *before* we perform dexopt on this package, so that
10980            // we can avoid redundant dexopts, and also to make sure we've got the
10981            // code and package path correct.
10982            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10983        }
10984
10985        if (mFactoryTest && pkg.requestedPermissions.contains(
10986                android.Manifest.permission.FACTORY_TEST)) {
10987            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10988        }
10989
10990        if (isSystemApp(pkg)) {
10991            pkgSetting.isOrphaned = true;
10992        }
10993
10994        // Take care of first install / last update times.
10995        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10996        if (currentTime != 0) {
10997            if (pkgSetting.firstInstallTime == 0) {
10998                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10999            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
11000                pkgSetting.lastUpdateTime = currentTime;
11001            }
11002        } else if (pkgSetting.firstInstallTime == 0) {
11003            // We need *something*.  Take time time stamp of the file.
11004            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
11005        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
11006            if (scanFileTime != pkgSetting.timeStamp) {
11007                // A package on the system image has changed; consider this
11008                // to be an update.
11009                pkgSetting.lastUpdateTime = scanFileTime;
11010            }
11011        }
11012        pkgSetting.setTimeStamp(scanFileTime);
11013
11014        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
11015            if (nonMutatedPs != null) {
11016                synchronized (mPackages) {
11017                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
11018                }
11019            }
11020        } else {
11021            final int userId = user == null ? 0 : user.getIdentifier();
11022            // Modify state for the given package setting
11023            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
11024                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
11025            if (pkgSetting.getInstantApp(userId)) {
11026                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
11027            }
11028        }
11029        return pkg;
11030    }
11031
11032    /**
11033     * Applies policy to the parsed package based upon the given policy flags.
11034     * Ensures the package is in a good state.
11035     * <p>
11036     * Implementation detail: This method must NOT have any side effect. It would
11037     * ideally be static, but, it requires locks to read system state.
11038     */
11039    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
11040        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
11041            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
11042            if (pkg.applicationInfo.isDirectBootAware()) {
11043                // we're direct boot aware; set for all components
11044                for (PackageParser.Service s : pkg.services) {
11045                    s.info.encryptionAware = s.info.directBootAware = true;
11046                }
11047                for (PackageParser.Provider p : pkg.providers) {
11048                    p.info.encryptionAware = p.info.directBootAware = true;
11049                }
11050                for (PackageParser.Activity a : pkg.activities) {
11051                    a.info.encryptionAware = a.info.directBootAware = true;
11052                }
11053                for (PackageParser.Activity r : pkg.receivers) {
11054                    r.info.encryptionAware = r.info.directBootAware = true;
11055                }
11056            }
11057            if (compressedFileExists(pkg.baseCodePath)) {
11058                pkg.isStub = true;
11059            }
11060        } else {
11061            // Only allow system apps to be flagged as core apps.
11062            pkg.coreApp = false;
11063            // clear flags not applicable to regular apps
11064            pkg.applicationInfo.privateFlags &=
11065                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
11066            pkg.applicationInfo.privateFlags &=
11067                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
11068        }
11069        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
11070
11071        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
11072            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
11073        }
11074
11075        if (!isSystemApp(pkg)) {
11076            // Only system apps can use these features.
11077            pkg.mOriginalPackages = null;
11078            pkg.mRealPackage = null;
11079            pkg.mAdoptPermissions = null;
11080        }
11081    }
11082
11083    /**
11084     * Asserts the parsed package is valid according to the given policy. If the
11085     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
11086     * <p>
11087     * Implementation detail: This method must NOT have any side effects. It would
11088     * ideally be static, but, it requires locks to read system state.
11089     *
11090     * @throws PackageManagerException If the package fails any of the validation checks
11091     */
11092    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
11093            throws PackageManagerException {
11094        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
11095            assertCodePolicy(pkg);
11096        }
11097
11098        if (pkg.applicationInfo.getCodePath() == null ||
11099                pkg.applicationInfo.getResourcePath() == null) {
11100            // Bail out. The resource and code paths haven't been set.
11101            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
11102                    "Code and resource paths haven't been set correctly");
11103        }
11104
11105        // Make sure we're not adding any bogus keyset info
11106        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11107        ksms.assertScannedPackageValid(pkg);
11108
11109        synchronized (mPackages) {
11110            // The special "android" package can only be defined once
11111            if (pkg.packageName.equals("android")) {
11112                if (mAndroidApplication != null) {
11113                    Slog.w(TAG, "*************************************************");
11114                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
11115                    Slog.w(TAG, " codePath=" + pkg.codePath);
11116                    Slog.w(TAG, "*************************************************");
11117                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11118                            "Core android package being redefined.  Skipping.");
11119                }
11120            }
11121
11122            // A package name must be unique; don't allow duplicates
11123            if (mPackages.containsKey(pkg.packageName)) {
11124                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11125                        "Application package " + pkg.packageName
11126                        + " already installed.  Skipping duplicate.");
11127            }
11128
11129            if (pkg.applicationInfo.isStaticSharedLibrary()) {
11130                // Static libs have a synthetic package name containing the version
11131                // but we still want the base name to be unique.
11132                if (mPackages.containsKey(pkg.manifestPackageName)) {
11133                    throw new PackageManagerException(
11134                            "Duplicate static shared lib provider package");
11135                }
11136
11137                // Static shared libraries should have at least O target SDK
11138                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
11139                    throw new PackageManagerException(
11140                            "Packages declaring static-shared libs must target O SDK or higher");
11141                }
11142
11143                // Package declaring static a shared lib cannot be instant apps
11144                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11145                    throw new PackageManagerException(
11146                            "Packages declaring static-shared libs cannot be instant apps");
11147                }
11148
11149                // Package declaring static a shared lib cannot be renamed since the package
11150                // name is synthetic and apps can't code around package manager internals.
11151                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
11152                    throw new PackageManagerException(
11153                            "Packages declaring static-shared libs cannot be renamed");
11154                }
11155
11156                // Package declaring static a shared lib cannot declare child packages
11157                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
11158                    throw new PackageManagerException(
11159                            "Packages declaring static-shared libs cannot have child packages");
11160                }
11161
11162                // Package declaring static a shared lib cannot declare dynamic libs
11163                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
11164                    throw new PackageManagerException(
11165                            "Packages declaring static-shared libs cannot declare dynamic libs");
11166                }
11167
11168                // Package declaring static a shared lib cannot declare shared users
11169                if (pkg.mSharedUserId != null) {
11170                    throw new PackageManagerException(
11171                            "Packages declaring static-shared libs cannot declare shared users");
11172                }
11173
11174                // Static shared libs cannot declare activities
11175                if (!pkg.activities.isEmpty()) {
11176                    throw new PackageManagerException(
11177                            "Static shared libs cannot declare activities");
11178                }
11179
11180                // Static shared libs cannot declare services
11181                if (!pkg.services.isEmpty()) {
11182                    throw new PackageManagerException(
11183                            "Static shared libs cannot declare services");
11184                }
11185
11186                // Static shared libs cannot declare providers
11187                if (!pkg.providers.isEmpty()) {
11188                    throw new PackageManagerException(
11189                            "Static shared libs cannot declare content providers");
11190                }
11191
11192                // Static shared libs cannot declare receivers
11193                if (!pkg.receivers.isEmpty()) {
11194                    throw new PackageManagerException(
11195                            "Static shared libs cannot declare broadcast receivers");
11196                }
11197
11198                // Static shared libs cannot declare permission groups
11199                if (!pkg.permissionGroups.isEmpty()) {
11200                    throw new PackageManagerException(
11201                            "Static shared libs cannot declare permission groups");
11202                }
11203
11204                // Static shared libs cannot declare permissions
11205                if (!pkg.permissions.isEmpty()) {
11206                    throw new PackageManagerException(
11207                            "Static shared libs cannot declare permissions");
11208                }
11209
11210                // Static shared libs cannot declare protected broadcasts
11211                if (pkg.protectedBroadcasts != null) {
11212                    throw new PackageManagerException(
11213                            "Static shared libs cannot declare protected broadcasts");
11214                }
11215
11216                // Static shared libs cannot be overlay targets
11217                if (pkg.mOverlayTarget != null) {
11218                    throw new PackageManagerException(
11219                            "Static shared libs cannot be overlay targets");
11220                }
11221
11222                // The version codes must be ordered as lib versions
11223                int minVersionCode = Integer.MIN_VALUE;
11224                int maxVersionCode = Integer.MAX_VALUE;
11225
11226                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
11227                        pkg.staticSharedLibName);
11228                if (versionedLib != null) {
11229                    final int versionCount = versionedLib.size();
11230                    for (int i = 0; i < versionCount; i++) {
11231                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
11232                        final int libVersionCode = libInfo.getDeclaringPackage()
11233                                .getVersionCode();
11234                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
11235                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
11236                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
11237                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
11238                        } else {
11239                            minVersionCode = maxVersionCode = libVersionCode;
11240                            break;
11241                        }
11242                    }
11243                }
11244                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
11245                    throw new PackageManagerException("Static shared"
11246                            + " lib version codes must be ordered as lib versions");
11247                }
11248            }
11249
11250            // Only privileged apps and updated privileged apps can add child packages.
11251            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
11252                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
11253                    throw new PackageManagerException("Only privileged apps can add child "
11254                            + "packages. Ignoring package " + pkg.packageName);
11255                }
11256                final int childCount = pkg.childPackages.size();
11257                for (int i = 0; i < childCount; i++) {
11258                    PackageParser.Package childPkg = pkg.childPackages.get(i);
11259                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
11260                            childPkg.packageName)) {
11261                        throw new PackageManagerException("Can't override child of "
11262                                + "another disabled app. Ignoring package " + pkg.packageName);
11263                    }
11264                }
11265            }
11266
11267            // If we're only installing presumed-existing packages, require that the
11268            // scanned APK is both already known and at the path previously established
11269            // for it.  Previously unknown packages we pick up normally, but if we have an
11270            // a priori expectation about this package's install presence, enforce it.
11271            // With a singular exception for new system packages. When an OTA contains
11272            // a new system package, we allow the codepath to change from a system location
11273            // to the user-installed location. If we don't allow this change, any newer,
11274            // user-installed version of the application will be ignored.
11275            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11276                if (mExpectingBetter.containsKey(pkg.packageName)) {
11277                    logCriticalInfo(Log.WARN,
11278                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11279                } else {
11280                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11281                    if (known != null) {
11282                        if (DEBUG_PACKAGE_SCANNING) {
11283                            Log.d(TAG, "Examining " + pkg.codePath
11284                                    + " and requiring known paths " + known.codePathString
11285                                    + " & " + known.resourcePathString);
11286                        }
11287                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11288                                || !pkg.applicationInfo.getResourcePath().equals(
11289                                        known.resourcePathString)) {
11290                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11291                                    "Application package " + pkg.packageName
11292                                    + " found at " + pkg.applicationInfo.getCodePath()
11293                                    + " but expected at " + known.codePathString
11294                                    + "; ignoring.");
11295                        }
11296                    }
11297                }
11298            }
11299
11300            // Verify that this new package doesn't have any content providers
11301            // that conflict with existing packages.  Only do this if the
11302            // package isn't already installed, since we don't want to break
11303            // things that are installed.
11304            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11305                final int N = pkg.providers.size();
11306                int i;
11307                for (i=0; i<N; i++) {
11308                    PackageParser.Provider p = pkg.providers.get(i);
11309                    if (p.info.authority != null) {
11310                        String names[] = p.info.authority.split(";");
11311                        for (int j = 0; j < names.length; j++) {
11312                            if (mProvidersByAuthority.containsKey(names[j])) {
11313                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11314                                final String otherPackageName =
11315                                        ((other != null && other.getComponentName() != null) ?
11316                                                other.getComponentName().getPackageName() : "?");
11317                                throw new PackageManagerException(
11318                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11319                                        "Can't install because provider name " + names[j]
11320                                                + " (in package " + pkg.applicationInfo.packageName
11321                                                + ") is already used by " + otherPackageName);
11322                            }
11323                        }
11324                    }
11325                }
11326            }
11327        }
11328    }
11329
11330    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
11331            int type, String declaringPackageName, int declaringVersionCode) {
11332        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11333        if (versionedLib == null) {
11334            versionedLib = new SparseArray<>();
11335            mSharedLibraries.put(name, versionedLib);
11336            if (type == SharedLibraryInfo.TYPE_STATIC) {
11337                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11338            }
11339        } else if (versionedLib.indexOfKey(version) >= 0) {
11340            return false;
11341        }
11342        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11343                version, type, declaringPackageName, declaringVersionCode);
11344        versionedLib.put(version, libEntry);
11345        return true;
11346    }
11347
11348    private boolean removeSharedLibraryLPw(String name, int version) {
11349        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11350        if (versionedLib == null) {
11351            return false;
11352        }
11353        final int libIdx = versionedLib.indexOfKey(version);
11354        if (libIdx < 0) {
11355            return false;
11356        }
11357        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11358        versionedLib.remove(version);
11359        if (versionedLib.size() <= 0) {
11360            mSharedLibraries.remove(name);
11361            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11362                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11363                        .getPackageName());
11364            }
11365        }
11366        return true;
11367    }
11368
11369    /**
11370     * Adds a scanned package to the system. When this method is finished, the package will
11371     * be available for query, resolution, etc...
11372     */
11373    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11374            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11375        final String pkgName = pkg.packageName;
11376        if (mCustomResolverComponentName != null &&
11377                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11378            setUpCustomResolverActivity(pkg);
11379        }
11380
11381        if (pkg.packageName.equals("android")) {
11382            synchronized (mPackages) {
11383                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11384                    // Set up information for our fall-back user intent resolution activity.
11385                    mPlatformPackage = pkg;
11386                    pkg.mVersionCode = mSdkVersion;
11387                    mAndroidApplication = pkg.applicationInfo;
11388                    if (!mResolverReplaced) {
11389                        mResolveActivity.applicationInfo = mAndroidApplication;
11390                        mResolveActivity.name = ResolverActivity.class.getName();
11391                        mResolveActivity.packageName = mAndroidApplication.packageName;
11392                        mResolveActivity.processName = "system:ui";
11393                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11394                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11395                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11396                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11397                        mResolveActivity.exported = true;
11398                        mResolveActivity.enabled = true;
11399                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11400                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11401                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11402                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11403                                | ActivityInfo.CONFIG_ORIENTATION
11404                                | ActivityInfo.CONFIG_KEYBOARD
11405                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11406                        mResolveInfo.activityInfo = mResolveActivity;
11407                        mResolveInfo.priority = 0;
11408                        mResolveInfo.preferredOrder = 0;
11409                        mResolveInfo.match = 0;
11410                        mResolveComponentName = new ComponentName(
11411                                mAndroidApplication.packageName, mResolveActivity.name);
11412                    }
11413                }
11414            }
11415        }
11416
11417        ArrayList<PackageParser.Package> clientLibPkgs = null;
11418        // writer
11419        synchronized (mPackages) {
11420            boolean hasStaticSharedLibs = false;
11421
11422            // Any app can add new static shared libraries
11423            if (pkg.staticSharedLibName != null) {
11424                // Static shared libs don't allow renaming as they have synthetic package
11425                // names to allow install of multiple versions, so use name from manifest.
11426                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11427                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11428                        pkg.manifestPackageName, pkg.mVersionCode)) {
11429                    hasStaticSharedLibs = true;
11430                } else {
11431                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11432                                + pkg.staticSharedLibName + " already exists; skipping");
11433                }
11434                // Static shared libs cannot be updated once installed since they
11435                // use synthetic package name which includes the version code, so
11436                // not need to update other packages's shared lib dependencies.
11437            }
11438
11439            if (!hasStaticSharedLibs
11440                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11441                // Only system apps can add new dynamic shared libraries.
11442                if (pkg.libraryNames != null) {
11443                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11444                        String name = pkg.libraryNames.get(i);
11445                        boolean allowed = false;
11446                        if (pkg.isUpdatedSystemApp()) {
11447                            // New library entries can only be added through the
11448                            // system image.  This is important to get rid of a lot
11449                            // of nasty edge cases: for example if we allowed a non-
11450                            // system update of the app to add a library, then uninstalling
11451                            // the update would make the library go away, and assumptions
11452                            // we made such as through app install filtering would now
11453                            // have allowed apps on the device which aren't compatible
11454                            // with it.  Better to just have the restriction here, be
11455                            // conservative, and create many fewer cases that can negatively
11456                            // impact the user experience.
11457                            final PackageSetting sysPs = mSettings
11458                                    .getDisabledSystemPkgLPr(pkg.packageName);
11459                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11460                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11461                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11462                                        allowed = true;
11463                                        break;
11464                                    }
11465                                }
11466                            }
11467                        } else {
11468                            allowed = true;
11469                        }
11470                        if (allowed) {
11471                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11472                                    SharedLibraryInfo.VERSION_UNDEFINED,
11473                                    SharedLibraryInfo.TYPE_DYNAMIC,
11474                                    pkg.packageName, pkg.mVersionCode)) {
11475                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11476                                        + name + " already exists; skipping");
11477                            }
11478                        } else {
11479                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11480                                    + name + " that is not declared on system image; skipping");
11481                        }
11482                    }
11483
11484                    if ((scanFlags & SCAN_BOOTING) == 0) {
11485                        // If we are not booting, we need to update any applications
11486                        // that are clients of our shared library.  If we are booting,
11487                        // this will all be done once the scan is complete.
11488                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11489                    }
11490                }
11491            }
11492        }
11493
11494        if ((scanFlags & SCAN_BOOTING) != 0) {
11495            // No apps can run during boot scan, so they don't need to be frozen
11496        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11497            // Caller asked to not kill app, so it's probably not frozen
11498        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11499            // Caller asked us to ignore frozen check for some reason; they
11500            // probably didn't know the package name
11501        } else {
11502            // We're doing major surgery on this package, so it better be frozen
11503            // right now to keep it from launching
11504            checkPackageFrozen(pkgName);
11505        }
11506
11507        // Also need to kill any apps that are dependent on the library.
11508        if (clientLibPkgs != null) {
11509            for (int i=0; i<clientLibPkgs.size(); i++) {
11510                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11511                killApplication(clientPkg.applicationInfo.packageName,
11512                        clientPkg.applicationInfo.uid, "update lib");
11513            }
11514        }
11515
11516        // writer
11517        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11518
11519        synchronized (mPackages) {
11520            // We don't expect installation to fail beyond this point
11521
11522            // Add the new setting to mSettings
11523            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11524            // Add the new setting to mPackages
11525            mPackages.put(pkg.applicationInfo.packageName, pkg);
11526            // Make sure we don't accidentally delete its data.
11527            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11528            while (iter.hasNext()) {
11529                PackageCleanItem item = iter.next();
11530                if (pkgName.equals(item.packageName)) {
11531                    iter.remove();
11532                }
11533            }
11534
11535            // Add the package's KeySets to the global KeySetManagerService
11536            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11537            ksms.addScannedPackageLPw(pkg);
11538
11539            int N = pkg.providers.size();
11540            StringBuilder r = null;
11541            int i;
11542            for (i=0; i<N; i++) {
11543                PackageParser.Provider p = pkg.providers.get(i);
11544                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11545                        p.info.processName);
11546                mProviders.addProvider(p);
11547                p.syncable = p.info.isSyncable;
11548                if (p.info.authority != null) {
11549                    String names[] = p.info.authority.split(";");
11550                    p.info.authority = null;
11551                    for (int j = 0; j < names.length; j++) {
11552                        if (j == 1 && p.syncable) {
11553                            // We only want the first authority for a provider to possibly be
11554                            // syncable, so if we already added this provider using a different
11555                            // authority clear the syncable flag. We copy the provider before
11556                            // changing it because the mProviders object contains a reference
11557                            // to a provider that we don't want to change.
11558                            // Only do this for the second authority since the resulting provider
11559                            // object can be the same for all future authorities for this provider.
11560                            p = new PackageParser.Provider(p);
11561                            p.syncable = false;
11562                        }
11563                        if (!mProvidersByAuthority.containsKey(names[j])) {
11564                            mProvidersByAuthority.put(names[j], p);
11565                            if (p.info.authority == null) {
11566                                p.info.authority = names[j];
11567                            } else {
11568                                p.info.authority = p.info.authority + ";" + names[j];
11569                            }
11570                            if (DEBUG_PACKAGE_SCANNING) {
11571                                if (chatty)
11572                                    Log.d(TAG, "Registered content provider: " + names[j]
11573                                            + ", className = " + p.info.name + ", isSyncable = "
11574                                            + p.info.isSyncable);
11575                            }
11576                        } else {
11577                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11578                            Slog.w(TAG, "Skipping provider name " + names[j] +
11579                                    " (in package " + pkg.applicationInfo.packageName +
11580                                    "): name already used by "
11581                                    + ((other != null && other.getComponentName() != null)
11582                                            ? other.getComponentName().getPackageName() : "?"));
11583                        }
11584                    }
11585                }
11586                if (chatty) {
11587                    if (r == null) {
11588                        r = new StringBuilder(256);
11589                    } else {
11590                        r.append(' ');
11591                    }
11592                    r.append(p.info.name);
11593                }
11594            }
11595            if (r != null) {
11596                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11597            }
11598
11599            N = pkg.services.size();
11600            r = null;
11601            for (i=0; i<N; i++) {
11602                PackageParser.Service s = pkg.services.get(i);
11603                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11604                        s.info.processName);
11605                mServices.addService(s);
11606                if (chatty) {
11607                    if (r == null) {
11608                        r = new StringBuilder(256);
11609                    } else {
11610                        r.append(' ');
11611                    }
11612                    r.append(s.info.name);
11613                }
11614            }
11615            if (r != null) {
11616                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11617            }
11618
11619            N = pkg.receivers.size();
11620            r = null;
11621            for (i=0; i<N; i++) {
11622                PackageParser.Activity a = pkg.receivers.get(i);
11623                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11624                        a.info.processName);
11625                mReceivers.addActivity(a, "receiver");
11626                if (chatty) {
11627                    if (r == null) {
11628                        r = new StringBuilder(256);
11629                    } else {
11630                        r.append(' ');
11631                    }
11632                    r.append(a.info.name);
11633                }
11634            }
11635            if (r != null) {
11636                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11637            }
11638
11639            N = pkg.activities.size();
11640            r = null;
11641            for (i=0; i<N; i++) {
11642                PackageParser.Activity a = pkg.activities.get(i);
11643                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11644                        a.info.processName);
11645                mActivities.addActivity(a, "activity");
11646                if (chatty) {
11647                    if (r == null) {
11648                        r = new StringBuilder(256);
11649                    } else {
11650                        r.append(' ');
11651                    }
11652                    r.append(a.info.name);
11653                }
11654            }
11655            if (r != null) {
11656                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11657            }
11658
11659            N = pkg.permissionGroups.size();
11660            r = null;
11661            for (i=0; i<N; i++) {
11662                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11663                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11664                final String curPackageName = cur == null ? null : cur.info.packageName;
11665                // Dont allow ephemeral apps to define new permission groups.
11666                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11667                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11668                            + pg.info.packageName
11669                            + " ignored: instant apps cannot define new permission groups.");
11670                    continue;
11671                }
11672                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11673                if (cur == null || isPackageUpdate) {
11674                    mPermissionGroups.put(pg.info.name, pg);
11675                    if (chatty) {
11676                        if (r == null) {
11677                            r = new StringBuilder(256);
11678                        } else {
11679                            r.append(' ');
11680                        }
11681                        if (isPackageUpdate) {
11682                            r.append("UPD:");
11683                        }
11684                        r.append(pg.info.name);
11685                    }
11686                } else {
11687                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11688                            + pg.info.packageName + " ignored: original from "
11689                            + cur.info.packageName);
11690                    if (chatty) {
11691                        if (r == null) {
11692                            r = new StringBuilder(256);
11693                        } else {
11694                            r.append(' ');
11695                        }
11696                        r.append("DUP:");
11697                        r.append(pg.info.name);
11698                    }
11699                }
11700            }
11701            if (r != null) {
11702                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11703            }
11704
11705            N = pkg.permissions.size();
11706            r = null;
11707            for (i=0; i<N; i++) {
11708                PackageParser.Permission p = pkg.permissions.get(i);
11709
11710                // Dont allow ephemeral apps to define new permissions.
11711                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11712                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11713                            + p.info.packageName
11714                            + " ignored: instant apps cannot define new permissions.");
11715                    continue;
11716                }
11717
11718                // Assume by default that we did not install this permission into the system.
11719                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11720
11721                // Now that permission groups have a special meaning, we ignore permission
11722                // groups for legacy apps to prevent unexpected behavior. In particular,
11723                // permissions for one app being granted to someone just because they happen
11724                // to be in a group defined by another app (before this had no implications).
11725                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11726                    p.group = mPermissionGroups.get(p.info.group);
11727                    // Warn for a permission in an unknown group.
11728                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11729                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11730                                + p.info.packageName + " in an unknown group " + p.info.group);
11731                    }
11732                }
11733
11734                ArrayMap<String, BasePermission> permissionMap =
11735                        p.tree ? mSettings.mPermissionTrees
11736                                : mSettings.mPermissions;
11737                BasePermission bp = permissionMap.get(p.info.name);
11738
11739                // Allow system apps to redefine non-system permissions
11740                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11741                    final boolean currentOwnerIsSystem = (bp.perm != null
11742                            && isSystemApp(bp.perm.owner));
11743                    if (isSystemApp(p.owner)) {
11744                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11745                            // It's a built-in permission and no owner, take ownership now
11746                            bp.packageSetting = pkgSetting;
11747                            bp.perm = p;
11748                            bp.uid = pkg.applicationInfo.uid;
11749                            bp.sourcePackage = p.info.packageName;
11750                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11751                        } else if (!currentOwnerIsSystem) {
11752                            String msg = "New decl " + p.owner + " of permission  "
11753                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11754                            reportSettingsProblem(Log.WARN, msg);
11755                            bp = null;
11756                        }
11757                    }
11758                }
11759
11760                if (bp == null) {
11761                    bp = new BasePermission(p.info.name, p.info.packageName,
11762                            BasePermission.TYPE_NORMAL);
11763                    permissionMap.put(p.info.name, bp);
11764                }
11765
11766                if (bp.perm == null) {
11767                    if (bp.sourcePackage == null
11768                            || bp.sourcePackage.equals(p.info.packageName)) {
11769                        BasePermission tree = findPermissionTreeLP(p.info.name);
11770                        if (tree == null
11771                                || tree.sourcePackage.equals(p.info.packageName)) {
11772                            bp.packageSetting = pkgSetting;
11773                            bp.perm = p;
11774                            bp.uid = pkg.applicationInfo.uid;
11775                            bp.sourcePackage = p.info.packageName;
11776                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11777                            if (chatty) {
11778                                if (r == null) {
11779                                    r = new StringBuilder(256);
11780                                } else {
11781                                    r.append(' ');
11782                                }
11783                                r.append(p.info.name);
11784                            }
11785                        } else {
11786                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11787                                    + p.info.packageName + " ignored: base tree "
11788                                    + tree.name + " is from package "
11789                                    + tree.sourcePackage);
11790                        }
11791                    } else {
11792                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11793                                + p.info.packageName + " ignored: original from "
11794                                + bp.sourcePackage);
11795                    }
11796                } else if (chatty) {
11797                    if (r == null) {
11798                        r = new StringBuilder(256);
11799                    } else {
11800                        r.append(' ');
11801                    }
11802                    r.append("DUP:");
11803                    r.append(p.info.name);
11804                }
11805                if (bp.perm == p) {
11806                    bp.protectionLevel = p.info.protectionLevel;
11807                }
11808            }
11809
11810            if (r != null) {
11811                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11812            }
11813
11814            N = pkg.instrumentation.size();
11815            r = null;
11816            for (i=0; i<N; i++) {
11817                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11818                a.info.packageName = pkg.applicationInfo.packageName;
11819                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11820                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11821                a.info.splitNames = pkg.splitNames;
11822                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11823                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11824                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11825                a.info.dataDir = pkg.applicationInfo.dataDir;
11826                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11827                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11828                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11829                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11830                mInstrumentation.put(a.getComponentName(), a);
11831                if (chatty) {
11832                    if (r == null) {
11833                        r = new StringBuilder(256);
11834                    } else {
11835                        r.append(' ');
11836                    }
11837                    r.append(a.info.name);
11838                }
11839            }
11840            if (r != null) {
11841                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11842            }
11843
11844            if (pkg.protectedBroadcasts != null) {
11845                N = pkg.protectedBroadcasts.size();
11846                synchronized (mProtectedBroadcasts) {
11847                    for (i = 0; i < N; i++) {
11848                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11849                    }
11850                }
11851            }
11852        }
11853
11854        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11855    }
11856
11857    /**
11858     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11859     * is derived purely on the basis of the contents of {@code scanFile} and
11860     * {@code cpuAbiOverride}.
11861     *
11862     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11863     */
11864    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11865                                 String cpuAbiOverride, boolean extractLibs,
11866                                 File appLib32InstallDir)
11867            throws PackageManagerException {
11868        // Give ourselves some initial paths; we'll come back for another
11869        // pass once we've determined ABI below.
11870        setNativeLibraryPaths(pkg, appLib32InstallDir);
11871
11872        // We would never need to extract libs for forward-locked and external packages,
11873        // since the container service will do it for us. We shouldn't attempt to
11874        // extract libs from system app when it was not updated.
11875        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11876                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11877            extractLibs = false;
11878        }
11879
11880        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11881        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11882
11883        NativeLibraryHelper.Handle handle = null;
11884        try {
11885            handle = NativeLibraryHelper.Handle.create(pkg);
11886            // TODO(multiArch): This can be null for apps that didn't go through the
11887            // usual installation process. We can calculate it again, like we
11888            // do during install time.
11889            //
11890            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11891            // unnecessary.
11892            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11893
11894            // Null out the abis so that they can be recalculated.
11895            pkg.applicationInfo.primaryCpuAbi = null;
11896            pkg.applicationInfo.secondaryCpuAbi = null;
11897            if (isMultiArch(pkg.applicationInfo)) {
11898                // Warn if we've set an abiOverride for multi-lib packages..
11899                // By definition, we need to copy both 32 and 64 bit libraries for
11900                // such packages.
11901                if (pkg.cpuAbiOverride != null
11902                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11903                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11904                }
11905
11906                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11907                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11908                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11909                    if (extractLibs) {
11910                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11911                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11912                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11913                                useIsaSpecificSubdirs);
11914                    } else {
11915                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11916                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11917                    }
11918                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11919                }
11920
11921                // Shared library native code should be in the APK zip aligned
11922                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11923                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11924                            "Shared library native lib extraction not supported");
11925                }
11926
11927                maybeThrowExceptionForMultiArchCopy(
11928                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11929
11930                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11931                    if (extractLibs) {
11932                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11933                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11934                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11935                                useIsaSpecificSubdirs);
11936                    } else {
11937                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11938                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11939                    }
11940                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11941                }
11942
11943                maybeThrowExceptionForMultiArchCopy(
11944                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11945
11946                if (abi64 >= 0) {
11947                    // Shared library native libs should be in the APK zip aligned
11948                    if (extractLibs && pkg.isLibrary()) {
11949                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11950                                "Shared library native lib extraction not supported");
11951                    }
11952                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11953                }
11954
11955                if (abi32 >= 0) {
11956                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11957                    if (abi64 >= 0) {
11958                        if (pkg.use32bitAbi) {
11959                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11960                            pkg.applicationInfo.primaryCpuAbi = abi;
11961                        } else {
11962                            pkg.applicationInfo.secondaryCpuAbi = abi;
11963                        }
11964                    } else {
11965                        pkg.applicationInfo.primaryCpuAbi = abi;
11966                    }
11967                }
11968            } else {
11969                String[] abiList = (cpuAbiOverride != null) ?
11970                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11971
11972                // Enable gross and lame hacks for apps that are built with old
11973                // SDK tools. We must scan their APKs for renderscript bitcode and
11974                // not launch them if it's present. Don't bother checking on devices
11975                // that don't have 64 bit support.
11976                boolean needsRenderScriptOverride = false;
11977                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11978                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11979                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11980                    needsRenderScriptOverride = true;
11981                }
11982
11983                final int copyRet;
11984                if (extractLibs) {
11985                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11986                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11987                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11988                } else {
11989                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11990                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11991                }
11992                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11993
11994                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11995                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11996                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11997                }
11998
11999                if (copyRet >= 0) {
12000                    // Shared libraries that have native libs must be multi-architecture
12001                    if (pkg.isLibrary()) {
12002                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12003                                "Shared library with native libs must be multiarch");
12004                    }
12005                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
12006                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
12007                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
12008                } else if (needsRenderScriptOverride) {
12009                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
12010                }
12011            }
12012        } catch (IOException ioe) {
12013            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
12014        } finally {
12015            IoUtils.closeQuietly(handle);
12016        }
12017
12018        // Now that we've calculated the ABIs and determined if it's an internal app,
12019        // we will go ahead and populate the nativeLibraryPath.
12020        setNativeLibraryPaths(pkg, appLib32InstallDir);
12021    }
12022
12023    /**
12024     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
12025     * i.e, so that all packages can be run inside a single process if required.
12026     *
12027     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
12028     * this function will either try and make the ABI for all packages in {@code packagesForUser}
12029     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
12030     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
12031     * updating a package that belongs to a shared user.
12032     *
12033     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
12034     * adds unnecessary complexity.
12035     */
12036    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
12037            PackageParser.Package scannedPackage) {
12038        String requiredInstructionSet = null;
12039        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
12040            requiredInstructionSet = VMRuntime.getInstructionSet(
12041                     scannedPackage.applicationInfo.primaryCpuAbi);
12042        }
12043
12044        PackageSetting requirer = null;
12045        for (PackageSetting ps : packagesForUser) {
12046            // If packagesForUser contains scannedPackage, we skip it. This will happen
12047            // when scannedPackage is an update of an existing package. Without this check,
12048            // we will never be able to change the ABI of any package belonging to a shared
12049            // user, even if it's compatible with other packages.
12050            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12051                if (ps.primaryCpuAbiString == null) {
12052                    continue;
12053                }
12054
12055                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
12056                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
12057                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
12058                    // this but there's not much we can do.
12059                    String errorMessage = "Instruction set mismatch, "
12060                            + ((requirer == null) ? "[caller]" : requirer)
12061                            + " requires " + requiredInstructionSet + " whereas " + ps
12062                            + " requires " + instructionSet;
12063                    Slog.w(TAG, errorMessage);
12064                }
12065
12066                if (requiredInstructionSet == null) {
12067                    requiredInstructionSet = instructionSet;
12068                    requirer = ps;
12069                }
12070            }
12071        }
12072
12073        if (requiredInstructionSet != null) {
12074            String adjustedAbi;
12075            if (requirer != null) {
12076                // requirer != null implies that either scannedPackage was null or that scannedPackage
12077                // did not require an ABI, in which case we have to adjust scannedPackage to match
12078                // the ABI of the set (which is the same as requirer's ABI)
12079                adjustedAbi = requirer.primaryCpuAbiString;
12080                if (scannedPackage != null) {
12081                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
12082                }
12083            } else {
12084                // requirer == null implies that we're updating all ABIs in the set to
12085                // match scannedPackage.
12086                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
12087            }
12088
12089            for (PackageSetting ps : packagesForUser) {
12090                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12091                    if (ps.primaryCpuAbiString != null) {
12092                        continue;
12093                    }
12094
12095                    ps.primaryCpuAbiString = adjustedAbi;
12096                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
12097                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
12098                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
12099                        if (DEBUG_ABI_SELECTION) {
12100                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
12101                                    + " (requirer="
12102                                    + (requirer != null ? requirer.pkg : "null")
12103                                    + ", scannedPackage="
12104                                    + (scannedPackage != null ? scannedPackage : "null")
12105                                    + ")");
12106                        }
12107                        try {
12108                            mInstaller.rmdex(ps.codePathString,
12109                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
12110                        } catch (InstallerException ignored) {
12111                        }
12112                    }
12113                }
12114            }
12115        }
12116    }
12117
12118    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
12119        synchronized (mPackages) {
12120            mResolverReplaced = true;
12121            // Set up information for custom user intent resolution activity.
12122            mResolveActivity.applicationInfo = pkg.applicationInfo;
12123            mResolveActivity.name = mCustomResolverComponentName.getClassName();
12124            mResolveActivity.packageName = pkg.applicationInfo.packageName;
12125            mResolveActivity.processName = pkg.applicationInfo.packageName;
12126            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
12127            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
12128                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12129            mResolveActivity.theme = 0;
12130            mResolveActivity.exported = true;
12131            mResolveActivity.enabled = true;
12132            mResolveInfo.activityInfo = mResolveActivity;
12133            mResolveInfo.priority = 0;
12134            mResolveInfo.preferredOrder = 0;
12135            mResolveInfo.match = 0;
12136            mResolveComponentName = mCustomResolverComponentName;
12137            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
12138                    mResolveComponentName);
12139        }
12140    }
12141
12142    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
12143        if (installerActivity == null) {
12144            if (DEBUG_EPHEMERAL) {
12145                Slog.d(TAG, "Clear ephemeral installer activity");
12146            }
12147            mInstantAppInstallerActivity = null;
12148            return;
12149        }
12150
12151        if (DEBUG_EPHEMERAL) {
12152            Slog.d(TAG, "Set ephemeral installer activity: "
12153                    + installerActivity.getComponentName());
12154        }
12155        // Set up information for ephemeral installer activity
12156        mInstantAppInstallerActivity = installerActivity;
12157        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
12158                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12159        mInstantAppInstallerActivity.exported = true;
12160        mInstantAppInstallerActivity.enabled = true;
12161        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
12162        mInstantAppInstallerInfo.priority = 0;
12163        mInstantAppInstallerInfo.preferredOrder = 1;
12164        mInstantAppInstallerInfo.isDefault = true;
12165        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
12166                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
12167    }
12168
12169    private static String calculateBundledApkRoot(final String codePathString) {
12170        final File codePath = new File(codePathString);
12171        final File codeRoot;
12172        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
12173            codeRoot = Environment.getRootDirectory();
12174        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
12175            codeRoot = Environment.getOemDirectory();
12176        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
12177            codeRoot = Environment.getVendorDirectory();
12178        } else {
12179            // Unrecognized code path; take its top real segment as the apk root:
12180            // e.g. /something/app/blah.apk => /something
12181            try {
12182                File f = codePath.getCanonicalFile();
12183                File parent = f.getParentFile();    // non-null because codePath is a file
12184                File tmp;
12185                while ((tmp = parent.getParentFile()) != null) {
12186                    f = parent;
12187                    parent = tmp;
12188                }
12189                codeRoot = f;
12190                Slog.w(TAG, "Unrecognized code path "
12191                        + codePath + " - using " + codeRoot);
12192            } catch (IOException e) {
12193                // Can't canonicalize the code path -- shenanigans?
12194                Slog.w(TAG, "Can't canonicalize code path " + codePath);
12195                return Environment.getRootDirectory().getPath();
12196            }
12197        }
12198        return codeRoot.getPath();
12199    }
12200
12201    /**
12202     * Derive and set the location of native libraries for the given package,
12203     * which varies depending on where and how the package was installed.
12204     */
12205    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
12206        final ApplicationInfo info = pkg.applicationInfo;
12207        final String codePath = pkg.codePath;
12208        final File codeFile = new File(codePath);
12209        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
12210        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
12211
12212        info.nativeLibraryRootDir = null;
12213        info.nativeLibraryRootRequiresIsa = false;
12214        info.nativeLibraryDir = null;
12215        info.secondaryNativeLibraryDir = null;
12216
12217        if (isApkFile(codeFile)) {
12218            // Monolithic install
12219            if (bundledApp) {
12220                // If "/system/lib64/apkname" exists, assume that is the per-package
12221                // native library directory to use; otherwise use "/system/lib/apkname".
12222                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
12223                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
12224                        getPrimaryInstructionSet(info));
12225
12226                // This is a bundled system app so choose the path based on the ABI.
12227                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
12228                // is just the default path.
12229                final String apkName = deriveCodePathName(codePath);
12230                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
12231                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
12232                        apkName).getAbsolutePath();
12233
12234                if (info.secondaryCpuAbi != null) {
12235                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
12236                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
12237                            secondaryLibDir, apkName).getAbsolutePath();
12238                }
12239            } else if (asecApp) {
12240                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
12241                        .getAbsolutePath();
12242            } else {
12243                final String apkName = deriveCodePathName(codePath);
12244                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
12245                        .getAbsolutePath();
12246            }
12247
12248            info.nativeLibraryRootRequiresIsa = false;
12249            info.nativeLibraryDir = info.nativeLibraryRootDir;
12250        } else {
12251            // Cluster install
12252            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
12253            info.nativeLibraryRootRequiresIsa = true;
12254
12255            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
12256                    getPrimaryInstructionSet(info)).getAbsolutePath();
12257
12258            if (info.secondaryCpuAbi != null) {
12259                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
12260                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
12261            }
12262        }
12263    }
12264
12265    /**
12266     * Calculate the abis and roots for a bundled app. These can uniquely
12267     * be determined from the contents of the system partition, i.e whether
12268     * it contains 64 or 32 bit shared libraries etc. We do not validate any
12269     * of this information, and instead assume that the system was built
12270     * sensibly.
12271     */
12272    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
12273                                           PackageSetting pkgSetting) {
12274        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
12275
12276        // If "/system/lib64/apkname" exists, assume that is the per-package
12277        // native library directory to use; otherwise use "/system/lib/apkname".
12278        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
12279        setBundledAppAbi(pkg, apkRoot, apkName);
12280        // pkgSetting might be null during rescan following uninstall of updates
12281        // to a bundled app, so accommodate that possibility.  The settings in
12282        // that case will be established later from the parsed package.
12283        //
12284        // If the settings aren't null, sync them up with what we've just derived.
12285        // note that apkRoot isn't stored in the package settings.
12286        if (pkgSetting != null) {
12287            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
12288            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
12289        }
12290    }
12291
12292    /**
12293     * Deduces the ABI of a bundled app and sets the relevant fields on the
12294     * parsed pkg object.
12295     *
12296     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
12297     *        under which system libraries are installed.
12298     * @param apkName the name of the installed package.
12299     */
12300    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
12301        final File codeFile = new File(pkg.codePath);
12302
12303        final boolean has64BitLibs;
12304        final boolean has32BitLibs;
12305        if (isApkFile(codeFile)) {
12306            // Monolithic install
12307            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12308            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12309        } else {
12310            // Cluster install
12311            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12312            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12313                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12314                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12315                has64BitLibs = (new File(rootDir, isa)).exists();
12316            } else {
12317                has64BitLibs = false;
12318            }
12319            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12320                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12321                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12322                has32BitLibs = (new File(rootDir, isa)).exists();
12323            } else {
12324                has32BitLibs = false;
12325            }
12326        }
12327
12328        if (has64BitLibs && !has32BitLibs) {
12329            // The package has 64 bit libs, but not 32 bit libs. Its primary
12330            // ABI should be 64 bit. We can safely assume here that the bundled
12331            // native libraries correspond to the most preferred ABI in the list.
12332
12333            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12334            pkg.applicationInfo.secondaryCpuAbi = null;
12335        } else if (has32BitLibs && !has64BitLibs) {
12336            // The package has 32 bit libs but not 64 bit libs. Its primary
12337            // ABI should be 32 bit.
12338
12339            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12340            pkg.applicationInfo.secondaryCpuAbi = null;
12341        } else if (has32BitLibs && has64BitLibs) {
12342            // The application has both 64 and 32 bit bundled libraries. We check
12343            // here that the app declares multiArch support, and warn if it doesn't.
12344            //
12345            // We will be lenient here and record both ABIs. The primary will be the
12346            // ABI that's higher on the list, i.e, a device that's configured to prefer
12347            // 64 bit apps will see a 64 bit primary ABI,
12348
12349            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12350                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12351            }
12352
12353            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12354                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12355                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12356            } else {
12357                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12358                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12359            }
12360        } else {
12361            pkg.applicationInfo.primaryCpuAbi = null;
12362            pkg.applicationInfo.secondaryCpuAbi = null;
12363        }
12364    }
12365
12366    private void killApplication(String pkgName, int appId, String reason) {
12367        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12368    }
12369
12370    private void killApplication(String pkgName, int appId, int userId, String reason) {
12371        // Request the ActivityManager to kill the process(only for existing packages)
12372        // so that we do not end up in a confused state while the user is still using the older
12373        // version of the application while the new one gets installed.
12374        final long token = Binder.clearCallingIdentity();
12375        try {
12376            IActivityManager am = ActivityManager.getService();
12377            if (am != null) {
12378                try {
12379                    am.killApplication(pkgName, appId, userId, reason);
12380                } catch (RemoteException e) {
12381                }
12382            }
12383        } finally {
12384            Binder.restoreCallingIdentity(token);
12385        }
12386    }
12387
12388    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12389        // Remove the parent package setting
12390        PackageSetting ps = (PackageSetting) pkg.mExtras;
12391        if (ps != null) {
12392            removePackageLI(ps, chatty);
12393        }
12394        // Remove the child package setting
12395        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12396        for (int i = 0; i < childCount; i++) {
12397            PackageParser.Package childPkg = pkg.childPackages.get(i);
12398            ps = (PackageSetting) childPkg.mExtras;
12399            if (ps != null) {
12400                removePackageLI(ps, chatty);
12401            }
12402        }
12403    }
12404
12405    void removePackageLI(PackageSetting ps, boolean chatty) {
12406        if (DEBUG_INSTALL) {
12407            if (chatty)
12408                Log.d(TAG, "Removing package " + ps.name);
12409        }
12410
12411        // writer
12412        synchronized (mPackages) {
12413            mPackages.remove(ps.name);
12414            final PackageParser.Package pkg = ps.pkg;
12415            if (pkg != null) {
12416                cleanPackageDataStructuresLILPw(pkg, chatty);
12417            }
12418        }
12419    }
12420
12421    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12422        if (DEBUG_INSTALL) {
12423            if (chatty)
12424                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12425        }
12426
12427        // writer
12428        synchronized (mPackages) {
12429            // Remove the parent package
12430            mPackages.remove(pkg.applicationInfo.packageName);
12431            cleanPackageDataStructuresLILPw(pkg, chatty);
12432
12433            // Remove the child packages
12434            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12435            for (int i = 0; i < childCount; i++) {
12436                PackageParser.Package childPkg = pkg.childPackages.get(i);
12437                mPackages.remove(childPkg.applicationInfo.packageName);
12438                cleanPackageDataStructuresLILPw(childPkg, chatty);
12439            }
12440        }
12441    }
12442
12443    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12444        int N = pkg.providers.size();
12445        StringBuilder r = null;
12446        int i;
12447        for (i=0; i<N; i++) {
12448            PackageParser.Provider p = pkg.providers.get(i);
12449            mProviders.removeProvider(p);
12450            if (p.info.authority == null) {
12451
12452                /* There was another ContentProvider with this authority when
12453                 * this app was installed so this authority is null,
12454                 * Ignore it as we don't have to unregister the provider.
12455                 */
12456                continue;
12457            }
12458            String names[] = p.info.authority.split(";");
12459            for (int j = 0; j < names.length; j++) {
12460                if (mProvidersByAuthority.get(names[j]) == p) {
12461                    mProvidersByAuthority.remove(names[j]);
12462                    if (DEBUG_REMOVE) {
12463                        if (chatty)
12464                            Log.d(TAG, "Unregistered content provider: " + names[j]
12465                                    + ", className = " + p.info.name + ", isSyncable = "
12466                                    + p.info.isSyncable);
12467                    }
12468                }
12469            }
12470            if (DEBUG_REMOVE && chatty) {
12471                if (r == null) {
12472                    r = new StringBuilder(256);
12473                } else {
12474                    r.append(' ');
12475                }
12476                r.append(p.info.name);
12477            }
12478        }
12479        if (r != null) {
12480            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12481        }
12482
12483        N = pkg.services.size();
12484        r = null;
12485        for (i=0; i<N; i++) {
12486            PackageParser.Service s = pkg.services.get(i);
12487            mServices.removeService(s);
12488            if (chatty) {
12489                if (r == null) {
12490                    r = new StringBuilder(256);
12491                } else {
12492                    r.append(' ');
12493                }
12494                r.append(s.info.name);
12495            }
12496        }
12497        if (r != null) {
12498            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12499        }
12500
12501        N = pkg.receivers.size();
12502        r = null;
12503        for (i=0; i<N; i++) {
12504            PackageParser.Activity a = pkg.receivers.get(i);
12505            mReceivers.removeActivity(a, "receiver");
12506            if (DEBUG_REMOVE && chatty) {
12507                if (r == null) {
12508                    r = new StringBuilder(256);
12509                } else {
12510                    r.append(' ');
12511                }
12512                r.append(a.info.name);
12513            }
12514        }
12515        if (r != null) {
12516            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12517        }
12518
12519        N = pkg.activities.size();
12520        r = null;
12521        for (i=0; i<N; i++) {
12522            PackageParser.Activity a = pkg.activities.get(i);
12523            mActivities.removeActivity(a, "activity");
12524            if (DEBUG_REMOVE && chatty) {
12525                if (r == null) {
12526                    r = new StringBuilder(256);
12527                } else {
12528                    r.append(' ');
12529                }
12530                r.append(a.info.name);
12531            }
12532        }
12533        if (r != null) {
12534            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12535        }
12536
12537        N = pkg.permissions.size();
12538        r = null;
12539        for (i=0; i<N; i++) {
12540            PackageParser.Permission p = pkg.permissions.get(i);
12541            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12542            if (bp == null) {
12543                bp = mSettings.mPermissionTrees.get(p.info.name);
12544            }
12545            if (bp != null && bp.perm == p) {
12546                bp.perm = null;
12547                if (DEBUG_REMOVE && chatty) {
12548                    if (r == null) {
12549                        r = new StringBuilder(256);
12550                    } else {
12551                        r.append(' ');
12552                    }
12553                    r.append(p.info.name);
12554                }
12555            }
12556            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12557                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12558                if (appOpPkgs != null) {
12559                    appOpPkgs.remove(pkg.packageName);
12560                }
12561            }
12562        }
12563        if (r != null) {
12564            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12565        }
12566
12567        N = pkg.requestedPermissions.size();
12568        r = null;
12569        for (i=0; i<N; i++) {
12570            String perm = pkg.requestedPermissions.get(i);
12571            BasePermission bp = mSettings.mPermissions.get(perm);
12572            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12573                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12574                if (appOpPkgs != null) {
12575                    appOpPkgs.remove(pkg.packageName);
12576                    if (appOpPkgs.isEmpty()) {
12577                        mAppOpPermissionPackages.remove(perm);
12578                    }
12579                }
12580            }
12581        }
12582        if (r != null) {
12583            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12584        }
12585
12586        N = pkg.instrumentation.size();
12587        r = null;
12588        for (i=0; i<N; i++) {
12589            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12590            mInstrumentation.remove(a.getComponentName());
12591            if (DEBUG_REMOVE && chatty) {
12592                if (r == null) {
12593                    r = new StringBuilder(256);
12594                } else {
12595                    r.append(' ');
12596                }
12597                r.append(a.info.name);
12598            }
12599        }
12600        if (r != null) {
12601            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12602        }
12603
12604        r = null;
12605        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12606            // Only system apps can hold shared libraries.
12607            if (pkg.libraryNames != null) {
12608                for (i = 0; i < pkg.libraryNames.size(); i++) {
12609                    String name = pkg.libraryNames.get(i);
12610                    if (removeSharedLibraryLPw(name, 0)) {
12611                        if (DEBUG_REMOVE && chatty) {
12612                            if (r == null) {
12613                                r = new StringBuilder(256);
12614                            } else {
12615                                r.append(' ');
12616                            }
12617                            r.append(name);
12618                        }
12619                    }
12620                }
12621            }
12622        }
12623
12624        r = null;
12625
12626        // Any package can hold static shared libraries.
12627        if (pkg.staticSharedLibName != null) {
12628            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12629                if (DEBUG_REMOVE && chatty) {
12630                    if (r == null) {
12631                        r = new StringBuilder(256);
12632                    } else {
12633                        r.append(' ');
12634                    }
12635                    r.append(pkg.staticSharedLibName);
12636                }
12637            }
12638        }
12639
12640        if (r != null) {
12641            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12642        }
12643    }
12644
12645    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12646        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12647            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12648                return true;
12649            }
12650        }
12651        return false;
12652    }
12653
12654    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12655    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12656    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12657
12658    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12659        // Update the parent permissions
12660        updatePermissionsLPw(pkg.packageName, pkg, flags);
12661        // Update the child permissions
12662        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12663        for (int i = 0; i < childCount; i++) {
12664            PackageParser.Package childPkg = pkg.childPackages.get(i);
12665            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12666        }
12667    }
12668
12669    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12670            int flags) {
12671        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12672        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12673    }
12674
12675    private void updatePermissionsLPw(String changingPkg,
12676            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12677        // Make sure there are no dangling permission trees.
12678        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12679        while (it.hasNext()) {
12680            final BasePermission bp = it.next();
12681            if (bp.packageSetting == null) {
12682                // We may not yet have parsed the package, so just see if
12683                // we still know about its settings.
12684                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12685            }
12686            if (bp.packageSetting == null) {
12687                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12688                        + " from package " + bp.sourcePackage);
12689                it.remove();
12690            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12691                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12692                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12693                            + " from package " + bp.sourcePackage);
12694                    flags |= UPDATE_PERMISSIONS_ALL;
12695                    it.remove();
12696                }
12697            }
12698        }
12699
12700        // Make sure all dynamic permissions have been assigned to a package,
12701        // and make sure there are no dangling permissions.
12702        it = mSettings.mPermissions.values().iterator();
12703        while (it.hasNext()) {
12704            final BasePermission bp = it.next();
12705            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12706                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12707                        + bp.name + " pkg=" + bp.sourcePackage
12708                        + " info=" + bp.pendingInfo);
12709                if (bp.packageSetting == null && bp.pendingInfo != null) {
12710                    final BasePermission tree = findPermissionTreeLP(bp.name);
12711                    if (tree != null && tree.perm != null) {
12712                        bp.packageSetting = tree.packageSetting;
12713                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12714                                new PermissionInfo(bp.pendingInfo));
12715                        bp.perm.info.packageName = tree.perm.info.packageName;
12716                        bp.perm.info.name = bp.name;
12717                        bp.uid = tree.uid;
12718                    }
12719                }
12720            }
12721            if (bp.packageSetting == null) {
12722                // We may not yet have parsed the package, so just see if
12723                // we still know about its settings.
12724                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12725            }
12726            if (bp.packageSetting == null) {
12727                Slog.w(TAG, "Removing dangling permission: " + bp.name
12728                        + " from package " + bp.sourcePackage);
12729                it.remove();
12730            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12731                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12732                    Slog.i(TAG, "Removing old permission: " + bp.name
12733                            + " from package " + bp.sourcePackage);
12734                    flags |= UPDATE_PERMISSIONS_ALL;
12735                    it.remove();
12736                }
12737            }
12738        }
12739
12740        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12741        // Now update the permissions for all packages, in particular
12742        // replace the granted permissions of the system packages.
12743        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12744            for (PackageParser.Package pkg : mPackages.values()) {
12745                if (pkg != pkgInfo) {
12746                    // Only replace for packages on requested volume
12747                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12748                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12749                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12750                    grantPermissionsLPw(pkg, replace, changingPkg);
12751                }
12752            }
12753        }
12754
12755        if (pkgInfo != null) {
12756            // Only replace for packages on requested volume
12757            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12758            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12759                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12760            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12761        }
12762        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12763    }
12764
12765    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12766            String packageOfInterest) {
12767        // IMPORTANT: There are two types of permissions: install and runtime.
12768        // Install time permissions are granted when the app is installed to
12769        // all device users and users added in the future. Runtime permissions
12770        // are granted at runtime explicitly to specific users. Normal and signature
12771        // protected permissions are install time permissions. Dangerous permissions
12772        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12773        // otherwise they are runtime permissions. This function does not manage
12774        // runtime permissions except for the case an app targeting Lollipop MR1
12775        // being upgraded to target a newer SDK, in which case dangerous permissions
12776        // are transformed from install time to runtime ones.
12777
12778        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12779        if (ps == null) {
12780            return;
12781        }
12782
12783        PermissionsState permissionsState = ps.getPermissionsState();
12784        PermissionsState origPermissions = permissionsState;
12785
12786        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12787
12788        boolean runtimePermissionsRevoked = false;
12789        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12790
12791        boolean changedInstallPermission = false;
12792
12793        if (replace) {
12794            ps.installPermissionsFixed = false;
12795            if (!ps.isSharedUser()) {
12796                origPermissions = new PermissionsState(permissionsState);
12797                permissionsState.reset();
12798            } else {
12799                // We need to know only about runtime permission changes since the
12800                // calling code always writes the install permissions state but
12801                // the runtime ones are written only if changed. The only cases of
12802                // changed runtime permissions here are promotion of an install to
12803                // runtime and revocation of a runtime from a shared user.
12804                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12805                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12806                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12807                    runtimePermissionsRevoked = true;
12808                }
12809            }
12810        }
12811
12812        permissionsState.setGlobalGids(mGlobalGids);
12813
12814        final int N = pkg.requestedPermissions.size();
12815        for (int i=0; i<N; i++) {
12816            final String name = pkg.requestedPermissions.get(i);
12817            final BasePermission bp = mSettings.mPermissions.get(name);
12818            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12819                    >= Build.VERSION_CODES.M;
12820
12821            if (DEBUG_INSTALL) {
12822                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12823            }
12824
12825            if (bp == null || bp.packageSetting == null) {
12826                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12827                    if (DEBUG_PERMISSIONS) {
12828                        Slog.i(TAG, "Unknown permission " + name
12829                                + " in package " + pkg.packageName);
12830                    }
12831                }
12832                continue;
12833            }
12834
12835
12836            // Limit ephemeral apps to ephemeral allowed permissions.
12837            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12838                if (DEBUG_PERMISSIONS) {
12839                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12840                            + pkg.packageName);
12841                }
12842                continue;
12843            }
12844
12845            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12846                if (DEBUG_PERMISSIONS) {
12847                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12848                            + pkg.packageName);
12849                }
12850                continue;
12851            }
12852
12853            final String perm = bp.name;
12854            boolean allowedSig = false;
12855            int grant = GRANT_DENIED;
12856
12857            // Keep track of app op permissions.
12858            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12859                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12860                if (pkgs == null) {
12861                    pkgs = new ArraySet<>();
12862                    mAppOpPermissionPackages.put(bp.name, pkgs);
12863                }
12864                pkgs.add(pkg.packageName);
12865            }
12866
12867            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12868            switch (level) {
12869                case PermissionInfo.PROTECTION_NORMAL: {
12870                    // For all apps normal permissions are install time ones.
12871                    grant = GRANT_INSTALL;
12872                } break;
12873
12874                case PermissionInfo.PROTECTION_DANGEROUS: {
12875                    // If a permission review is required for legacy apps we represent
12876                    // their permissions as always granted runtime ones since we need
12877                    // to keep the review required permission flag per user while an
12878                    // install permission's state is shared across all users.
12879                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12880                        // For legacy apps dangerous permissions are install time ones.
12881                        grant = GRANT_INSTALL;
12882                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12883                        // For legacy apps that became modern, install becomes runtime.
12884                        grant = GRANT_UPGRADE;
12885                    } else if (mPromoteSystemApps
12886                            && isSystemApp(ps)
12887                            && mExistingSystemPackages.contains(ps.name)) {
12888                        // For legacy system apps, install becomes runtime.
12889                        // We cannot check hasInstallPermission() for system apps since those
12890                        // permissions were granted implicitly and not persisted pre-M.
12891                        grant = GRANT_UPGRADE;
12892                    } else {
12893                        // For modern apps keep runtime permissions unchanged.
12894                        grant = GRANT_RUNTIME;
12895                    }
12896                } break;
12897
12898                case PermissionInfo.PROTECTION_SIGNATURE: {
12899                    // For all apps signature permissions are install time ones.
12900                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12901                    if (allowedSig) {
12902                        grant = GRANT_INSTALL;
12903                    }
12904                } break;
12905            }
12906
12907            if (DEBUG_PERMISSIONS) {
12908                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12909            }
12910
12911            if (grant != GRANT_DENIED) {
12912                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12913                    // If this is an existing, non-system package, then
12914                    // we can't add any new permissions to it.
12915                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12916                        // Except...  if this is a permission that was added
12917                        // to the platform (note: need to only do this when
12918                        // updating the platform).
12919                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12920                            grant = GRANT_DENIED;
12921                        }
12922                    }
12923                }
12924
12925                switch (grant) {
12926                    case GRANT_INSTALL: {
12927                        // Revoke this as runtime permission to handle the case of
12928                        // a runtime permission being downgraded to an install one.
12929                        // Also in permission review mode we keep dangerous permissions
12930                        // for legacy apps
12931                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12932                            if (origPermissions.getRuntimePermissionState(
12933                                    bp.name, userId) != null) {
12934                                // Revoke the runtime permission and clear the flags.
12935                                origPermissions.revokeRuntimePermission(bp, userId);
12936                                origPermissions.updatePermissionFlags(bp, userId,
12937                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12938                                // If we revoked a permission permission, we have to write.
12939                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12940                                        changedRuntimePermissionUserIds, userId);
12941                            }
12942                        }
12943                        // Grant an install permission.
12944                        if (permissionsState.grantInstallPermission(bp) !=
12945                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12946                            changedInstallPermission = true;
12947                        }
12948                    } break;
12949
12950                    case GRANT_RUNTIME: {
12951                        // Grant previously granted runtime permissions.
12952                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12953                            PermissionState permissionState = origPermissions
12954                                    .getRuntimePermissionState(bp.name, userId);
12955                            int flags = permissionState != null
12956                                    ? permissionState.getFlags() : 0;
12957                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12958                                // Don't propagate the permission in a permission review mode if
12959                                // the former was revoked, i.e. marked to not propagate on upgrade.
12960                                // Note that in a permission review mode install permissions are
12961                                // represented as constantly granted runtime ones since we need to
12962                                // keep a per user state associated with the permission. Also the
12963                                // revoke on upgrade flag is no longer applicable and is reset.
12964                                final boolean revokeOnUpgrade = (flags & PackageManager
12965                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12966                                if (revokeOnUpgrade) {
12967                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12968                                    // Since we changed the flags, we have to write.
12969                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12970                                            changedRuntimePermissionUserIds, userId);
12971                                }
12972                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12973                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12974                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12975                                        // If we cannot put the permission as it was,
12976                                        // we have to write.
12977                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12978                                                changedRuntimePermissionUserIds, userId);
12979                                    }
12980                                }
12981
12982                                // If the app supports runtime permissions no need for a review.
12983                                if (mPermissionReviewRequired
12984                                        && appSupportsRuntimePermissions
12985                                        && (flags & PackageManager
12986                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12987                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12988                                    // Since we changed the flags, we have to write.
12989                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12990                                            changedRuntimePermissionUserIds, userId);
12991                                }
12992                            } else if (mPermissionReviewRequired
12993                                    && !appSupportsRuntimePermissions) {
12994                                // For legacy apps that need a permission review, every new
12995                                // runtime permission is granted but it is pending a review.
12996                                // We also need to review only platform defined runtime
12997                                // permissions as these are the only ones the platform knows
12998                                // how to disable the API to simulate revocation as legacy
12999                                // apps don't expect to run with revoked permissions.
13000                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
13001                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
13002                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
13003                                        // We changed the flags, hence have to write.
13004                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13005                                                changedRuntimePermissionUserIds, userId);
13006                                    }
13007                                }
13008                                if (permissionsState.grantRuntimePermission(bp, userId)
13009                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13010                                    // We changed the permission, hence have to write.
13011                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13012                                            changedRuntimePermissionUserIds, userId);
13013                                }
13014                            }
13015                            // Propagate the permission flags.
13016                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
13017                        }
13018                    } break;
13019
13020                    case GRANT_UPGRADE: {
13021                        // Grant runtime permissions for a previously held install permission.
13022                        PermissionState permissionState = origPermissions
13023                                .getInstallPermissionState(bp.name);
13024                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
13025
13026                        if (origPermissions.revokeInstallPermission(bp)
13027                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
13028                            // We will be transferring the permission flags, so clear them.
13029                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
13030                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
13031                            changedInstallPermission = true;
13032                        }
13033
13034                        // If the permission is not to be promoted to runtime we ignore it and
13035                        // also its other flags as they are not applicable to install permissions.
13036                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
13037                            for (int userId : currentUserIds) {
13038                                if (permissionsState.grantRuntimePermission(bp, userId) !=
13039                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13040                                    // Transfer the permission flags.
13041                                    permissionsState.updatePermissionFlags(bp, userId,
13042                                            flags, flags);
13043                                    // If we granted the permission, we have to write.
13044                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
13045                                            changedRuntimePermissionUserIds, userId);
13046                                }
13047                            }
13048                        }
13049                    } break;
13050
13051                    default: {
13052                        if (packageOfInterest == null
13053                                || packageOfInterest.equals(pkg.packageName)) {
13054                            if (DEBUG_PERMISSIONS) {
13055                                Slog.i(TAG, "Not granting permission " + perm
13056                                        + " to package " + pkg.packageName
13057                                        + " because it was previously installed without");
13058                            }
13059                        }
13060                    } break;
13061                }
13062            } else {
13063                if (permissionsState.revokeInstallPermission(bp) !=
13064                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13065                    // Also drop the permission flags.
13066                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13067                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13068                    changedInstallPermission = true;
13069                    Slog.i(TAG, "Un-granting permission " + perm
13070                            + " from package " + pkg.packageName
13071                            + " (protectionLevel=" + bp.protectionLevel
13072                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13073                            + ")");
13074                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
13075                    // Don't print warning for app op permissions, since it is fine for them
13076                    // not to be granted, there is a UI for the user to decide.
13077                    if (DEBUG_PERMISSIONS
13078                            && (packageOfInterest == null
13079                                    || packageOfInterest.equals(pkg.packageName))) {
13080                        Slog.i(TAG, "Not granting permission " + perm
13081                                + " to package " + pkg.packageName
13082                                + " (protectionLevel=" + bp.protectionLevel
13083                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13084                                + ")");
13085                    }
13086                }
13087            }
13088        }
13089
13090        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
13091                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
13092            // This is the first that we have heard about this package, so the
13093            // permissions we have now selected are fixed until explicitly
13094            // changed.
13095            ps.installPermissionsFixed = true;
13096        }
13097
13098        // Persist the runtime permissions state for users with changes. If permissions
13099        // were revoked because no app in the shared user declares them we have to
13100        // write synchronously to avoid losing runtime permissions state.
13101        for (int userId : changedRuntimePermissionUserIds) {
13102            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
13103        }
13104    }
13105
13106    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
13107        boolean allowed = false;
13108        final int NP = PackageParser.NEW_PERMISSIONS.length;
13109        for (int ip=0; ip<NP; ip++) {
13110            final PackageParser.NewPermissionInfo npi
13111                    = PackageParser.NEW_PERMISSIONS[ip];
13112            if (npi.name.equals(perm)
13113                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
13114                allowed = true;
13115                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
13116                        + pkg.packageName);
13117                break;
13118            }
13119        }
13120        return allowed;
13121    }
13122
13123    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
13124            BasePermission bp, PermissionsState origPermissions) {
13125        boolean privilegedPermission = (bp.protectionLevel
13126                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
13127        boolean privappPermissionsDisable =
13128                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
13129        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
13130        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
13131        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
13132                && !platformPackage && platformPermission) {
13133            ArraySet<String> wlPermissions = SystemConfig.getInstance()
13134                    .getPrivAppPermissions(pkg.packageName);
13135            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
13136            if (!whitelisted) {
13137                Slog.w(TAG, "Privileged permission " + perm + " for package "
13138                        + pkg.packageName + " - not in privapp-permissions whitelist");
13139                // Only report violations for apps on system image
13140                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
13141                    if (mPrivappPermissionsViolations == null) {
13142                        mPrivappPermissionsViolations = new ArraySet<>();
13143                    }
13144                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
13145                }
13146                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
13147                    return false;
13148                }
13149            }
13150        }
13151        boolean allowed = (compareSignatures(
13152                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
13153                        == PackageManager.SIGNATURE_MATCH)
13154                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
13155                        == PackageManager.SIGNATURE_MATCH);
13156        if (!allowed && privilegedPermission) {
13157            if (isSystemApp(pkg)) {
13158                // For updated system applications, a system permission
13159                // is granted only if it had been defined by the original application.
13160                if (pkg.isUpdatedSystemApp()) {
13161                    final PackageSetting sysPs = mSettings
13162                            .getDisabledSystemPkgLPr(pkg.packageName);
13163                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
13164                        // If the original was granted this permission, we take
13165                        // that grant decision as read and propagate it to the
13166                        // update.
13167                        if (sysPs.isPrivileged()) {
13168                            allowed = true;
13169                        }
13170                    } else {
13171                        // The system apk may have been updated with an older
13172                        // version of the one on the data partition, but which
13173                        // granted a new system permission that it didn't have
13174                        // before.  In this case we do want to allow the app to
13175                        // now get the new permission if the ancestral apk is
13176                        // privileged to get it.
13177                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
13178                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
13179                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
13180                                    allowed = true;
13181                                    break;
13182                                }
13183                            }
13184                        }
13185                        // Also if a privileged parent package on the system image or any of
13186                        // its children requested a privileged permission, the updated child
13187                        // packages can also get the permission.
13188                        if (pkg.parentPackage != null) {
13189                            final PackageSetting disabledSysParentPs = mSettings
13190                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
13191                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
13192                                    && disabledSysParentPs.isPrivileged()) {
13193                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
13194                                    allowed = true;
13195                                } else if (disabledSysParentPs.pkg.childPackages != null) {
13196                                    final int count = disabledSysParentPs.pkg.childPackages.size();
13197                                    for (int i = 0; i < count; i++) {
13198                                        PackageParser.Package disabledSysChildPkg =
13199                                                disabledSysParentPs.pkg.childPackages.get(i);
13200                                        if (isPackageRequestingPermission(disabledSysChildPkg,
13201                                                perm)) {
13202                                            allowed = true;
13203                                            break;
13204                                        }
13205                                    }
13206                                }
13207                            }
13208                        }
13209                    }
13210                } else {
13211                    allowed = isPrivilegedApp(pkg);
13212                }
13213            }
13214        }
13215        if (!allowed) {
13216            if (!allowed && (bp.protectionLevel
13217                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
13218                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
13219                // If this was a previously normal/dangerous permission that got moved
13220                // to a system permission as part of the runtime permission redesign, then
13221                // we still want to blindly grant it to old apps.
13222                allowed = true;
13223            }
13224            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
13225                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
13226                // If this permission is to be granted to the system installer and
13227                // this app is an installer, then it gets the permission.
13228                allowed = true;
13229            }
13230            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
13231                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
13232                // If this permission is to be granted to the system verifier and
13233                // this app is a verifier, then it gets the permission.
13234                allowed = true;
13235            }
13236            if (!allowed && (bp.protectionLevel
13237                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
13238                    && isSystemApp(pkg)) {
13239                // Any pre-installed system app is allowed to get this permission.
13240                allowed = true;
13241            }
13242            if (!allowed && (bp.protectionLevel
13243                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
13244                // For development permissions, a development permission
13245                // is granted only if it was already granted.
13246                allowed = origPermissions.hasInstallPermission(perm);
13247            }
13248            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
13249                    && pkg.packageName.equals(mSetupWizardPackage)) {
13250                // If this permission is to be granted to the system setup wizard and
13251                // this app is a setup wizard, then it gets the permission.
13252                allowed = true;
13253            }
13254        }
13255        return allowed;
13256    }
13257
13258    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
13259        final int permCount = pkg.requestedPermissions.size();
13260        for (int j = 0; j < permCount; j++) {
13261            String requestedPermission = pkg.requestedPermissions.get(j);
13262            if (permission.equals(requestedPermission)) {
13263                return true;
13264            }
13265        }
13266        return false;
13267    }
13268
13269    final class ActivityIntentResolver
13270            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
13271        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13272                boolean defaultOnly, int userId) {
13273            if (!sUserManager.exists(userId)) return null;
13274            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
13275            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13276        }
13277
13278        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13279                int userId) {
13280            if (!sUserManager.exists(userId)) return null;
13281            mFlags = flags;
13282            return super.queryIntent(intent, resolvedType,
13283                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13284                    userId);
13285        }
13286
13287        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13288                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
13289            if (!sUserManager.exists(userId)) return null;
13290            if (packageActivities == null) {
13291                return null;
13292            }
13293            mFlags = flags;
13294            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13295            final int N = packageActivities.size();
13296            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
13297                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
13298
13299            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
13300            for (int i = 0; i < N; ++i) {
13301                intentFilters = packageActivities.get(i).intents;
13302                if (intentFilters != null && intentFilters.size() > 0) {
13303                    PackageParser.ActivityIntentInfo[] array =
13304                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
13305                    intentFilters.toArray(array);
13306                    listCut.add(array);
13307                }
13308            }
13309            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13310        }
13311
13312        /**
13313         * Finds a privileged activity that matches the specified activity names.
13314         */
13315        private PackageParser.Activity findMatchingActivity(
13316                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
13317            for (PackageParser.Activity sysActivity : activityList) {
13318                if (sysActivity.info.name.equals(activityInfo.name)) {
13319                    return sysActivity;
13320                }
13321                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
13322                    return sysActivity;
13323                }
13324                if (sysActivity.info.targetActivity != null) {
13325                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
13326                        return sysActivity;
13327                    }
13328                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
13329                        return sysActivity;
13330                    }
13331                }
13332            }
13333            return null;
13334        }
13335
13336        public class IterGenerator<E> {
13337            public Iterator<E> generate(ActivityIntentInfo info) {
13338                return null;
13339            }
13340        }
13341
13342        public class ActionIterGenerator extends IterGenerator<String> {
13343            @Override
13344            public Iterator<String> generate(ActivityIntentInfo info) {
13345                return info.actionsIterator();
13346            }
13347        }
13348
13349        public class CategoriesIterGenerator extends IterGenerator<String> {
13350            @Override
13351            public Iterator<String> generate(ActivityIntentInfo info) {
13352                return info.categoriesIterator();
13353            }
13354        }
13355
13356        public class SchemesIterGenerator extends IterGenerator<String> {
13357            @Override
13358            public Iterator<String> generate(ActivityIntentInfo info) {
13359                return info.schemesIterator();
13360            }
13361        }
13362
13363        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13364            @Override
13365            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13366                return info.authoritiesIterator();
13367            }
13368        }
13369
13370        /**
13371         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13372         * MODIFIED. Do not pass in a list that should not be changed.
13373         */
13374        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13375                IterGenerator<T> generator, Iterator<T> searchIterator) {
13376            // loop through the set of actions; every one must be found in the intent filter
13377            while (searchIterator.hasNext()) {
13378                // we must have at least one filter in the list to consider a match
13379                if (intentList.size() == 0) {
13380                    break;
13381                }
13382
13383                final T searchAction = searchIterator.next();
13384
13385                // loop through the set of intent filters
13386                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13387                while (intentIter.hasNext()) {
13388                    final ActivityIntentInfo intentInfo = intentIter.next();
13389                    boolean selectionFound = false;
13390
13391                    // loop through the intent filter's selection criteria; at least one
13392                    // of them must match the searched criteria
13393                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13394                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13395                        final T intentSelection = intentSelectionIter.next();
13396                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13397                            selectionFound = true;
13398                            break;
13399                        }
13400                    }
13401
13402                    // the selection criteria wasn't found in this filter's set; this filter
13403                    // is not a potential match
13404                    if (!selectionFound) {
13405                        intentIter.remove();
13406                    }
13407                }
13408            }
13409        }
13410
13411        private boolean isProtectedAction(ActivityIntentInfo filter) {
13412            final Iterator<String> actionsIter = filter.actionsIterator();
13413            while (actionsIter != null && actionsIter.hasNext()) {
13414                final String filterAction = actionsIter.next();
13415                if (PROTECTED_ACTIONS.contains(filterAction)) {
13416                    return true;
13417                }
13418            }
13419            return false;
13420        }
13421
13422        /**
13423         * Adjusts the priority of the given intent filter according to policy.
13424         * <p>
13425         * <ul>
13426         * <li>The priority for non privileged applications is capped to '0'</li>
13427         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13428         * <li>The priority for unbundled updates to privileged applications is capped to the
13429         *      priority defined on the system partition</li>
13430         * </ul>
13431         * <p>
13432         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13433         * allowed to obtain any priority on any action.
13434         */
13435        private void adjustPriority(
13436                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13437            // nothing to do; priority is fine as-is
13438            if (intent.getPriority() <= 0) {
13439                return;
13440            }
13441
13442            final ActivityInfo activityInfo = intent.activity.info;
13443            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13444
13445            final boolean privilegedApp =
13446                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13447            if (!privilegedApp) {
13448                // non-privileged applications can never define a priority >0
13449                if (DEBUG_FILTERS) {
13450                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13451                            + " package: " + applicationInfo.packageName
13452                            + " activity: " + intent.activity.className
13453                            + " origPrio: " + intent.getPriority());
13454                }
13455                intent.setPriority(0);
13456                return;
13457            }
13458
13459            if (systemActivities == null) {
13460                // the system package is not disabled; we're parsing the system partition
13461                if (isProtectedAction(intent)) {
13462                    if (mDeferProtectedFilters) {
13463                        // We can't deal with these just yet. No component should ever obtain a
13464                        // >0 priority for a protected actions, with ONE exception -- the setup
13465                        // wizard. The setup wizard, however, cannot be known until we're able to
13466                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13467                        // until all intent filters have been processed. Chicken, meet egg.
13468                        // Let the filter temporarily have a high priority and rectify the
13469                        // priorities after all system packages have been scanned.
13470                        mProtectedFilters.add(intent);
13471                        if (DEBUG_FILTERS) {
13472                            Slog.i(TAG, "Protected action; save for later;"
13473                                    + " package: " + applicationInfo.packageName
13474                                    + " activity: " + intent.activity.className
13475                                    + " origPrio: " + intent.getPriority());
13476                        }
13477                        return;
13478                    } else {
13479                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13480                            Slog.i(TAG, "No setup wizard;"
13481                                + " All protected intents capped to priority 0");
13482                        }
13483                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13484                            if (DEBUG_FILTERS) {
13485                                Slog.i(TAG, "Found setup wizard;"
13486                                    + " allow priority " + intent.getPriority() + ";"
13487                                    + " package: " + intent.activity.info.packageName
13488                                    + " activity: " + intent.activity.className
13489                                    + " priority: " + intent.getPriority());
13490                            }
13491                            // setup wizard gets whatever it wants
13492                            return;
13493                        }
13494                        if (DEBUG_FILTERS) {
13495                            Slog.i(TAG, "Protected action; cap priority to 0;"
13496                                    + " package: " + intent.activity.info.packageName
13497                                    + " activity: " + intent.activity.className
13498                                    + " origPrio: " + intent.getPriority());
13499                        }
13500                        intent.setPriority(0);
13501                        return;
13502                    }
13503                }
13504                // privileged apps on the system image get whatever priority they request
13505                return;
13506            }
13507
13508            // privileged app unbundled update ... try to find the same activity
13509            final PackageParser.Activity foundActivity =
13510                    findMatchingActivity(systemActivities, activityInfo);
13511            if (foundActivity == null) {
13512                // this is a new activity; it cannot obtain >0 priority
13513                if (DEBUG_FILTERS) {
13514                    Slog.i(TAG, "New activity; cap priority to 0;"
13515                            + " package: " + applicationInfo.packageName
13516                            + " activity: " + intent.activity.className
13517                            + " origPrio: " + intent.getPriority());
13518                }
13519                intent.setPriority(0);
13520                return;
13521            }
13522
13523            // found activity, now check for filter equivalence
13524
13525            // a shallow copy is enough; we modify the list, not its contents
13526            final List<ActivityIntentInfo> intentListCopy =
13527                    new ArrayList<>(foundActivity.intents);
13528            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13529
13530            // find matching action subsets
13531            final Iterator<String> actionsIterator = intent.actionsIterator();
13532            if (actionsIterator != null) {
13533                getIntentListSubset(
13534                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13535                if (intentListCopy.size() == 0) {
13536                    // no more intents to match; we're not equivalent
13537                    if (DEBUG_FILTERS) {
13538                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13539                                + " package: " + applicationInfo.packageName
13540                                + " activity: " + intent.activity.className
13541                                + " origPrio: " + intent.getPriority());
13542                    }
13543                    intent.setPriority(0);
13544                    return;
13545                }
13546            }
13547
13548            // find matching category subsets
13549            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13550            if (categoriesIterator != null) {
13551                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13552                        categoriesIterator);
13553                if (intentListCopy.size() == 0) {
13554                    // no more intents to match; we're not equivalent
13555                    if (DEBUG_FILTERS) {
13556                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13557                                + " package: " + applicationInfo.packageName
13558                                + " activity: " + intent.activity.className
13559                                + " origPrio: " + intent.getPriority());
13560                    }
13561                    intent.setPriority(0);
13562                    return;
13563                }
13564            }
13565
13566            // find matching schemes subsets
13567            final Iterator<String> schemesIterator = intent.schemesIterator();
13568            if (schemesIterator != null) {
13569                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13570                        schemesIterator);
13571                if (intentListCopy.size() == 0) {
13572                    // no more intents to match; we're not equivalent
13573                    if (DEBUG_FILTERS) {
13574                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13575                                + " package: " + applicationInfo.packageName
13576                                + " activity: " + intent.activity.className
13577                                + " origPrio: " + intent.getPriority());
13578                    }
13579                    intent.setPriority(0);
13580                    return;
13581                }
13582            }
13583
13584            // find matching authorities subsets
13585            final Iterator<IntentFilter.AuthorityEntry>
13586                    authoritiesIterator = intent.authoritiesIterator();
13587            if (authoritiesIterator != null) {
13588                getIntentListSubset(intentListCopy,
13589                        new AuthoritiesIterGenerator(),
13590                        authoritiesIterator);
13591                if (intentListCopy.size() == 0) {
13592                    // no more intents to match; we're not equivalent
13593                    if (DEBUG_FILTERS) {
13594                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13595                                + " package: " + applicationInfo.packageName
13596                                + " activity: " + intent.activity.className
13597                                + " origPrio: " + intent.getPriority());
13598                    }
13599                    intent.setPriority(0);
13600                    return;
13601                }
13602            }
13603
13604            // we found matching filter(s); app gets the max priority of all intents
13605            int cappedPriority = 0;
13606            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13607                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13608            }
13609            if (intent.getPriority() > cappedPriority) {
13610                if (DEBUG_FILTERS) {
13611                    Slog.i(TAG, "Found matching filter(s);"
13612                            + " cap priority to " + cappedPriority + ";"
13613                            + " package: " + applicationInfo.packageName
13614                            + " activity: " + intent.activity.className
13615                            + " origPrio: " + intent.getPriority());
13616                }
13617                intent.setPriority(cappedPriority);
13618                return;
13619            }
13620            // all this for nothing; the requested priority was <= what was on the system
13621        }
13622
13623        public final void addActivity(PackageParser.Activity a, String type) {
13624            mActivities.put(a.getComponentName(), a);
13625            if (DEBUG_SHOW_INFO)
13626                Log.v(
13627                TAG, "  " + type + " " +
13628                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13629            if (DEBUG_SHOW_INFO)
13630                Log.v(TAG, "    Class=" + a.info.name);
13631            final int NI = a.intents.size();
13632            for (int j=0; j<NI; j++) {
13633                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13634                if ("activity".equals(type)) {
13635                    final PackageSetting ps =
13636                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13637                    final List<PackageParser.Activity> systemActivities =
13638                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13639                    adjustPriority(systemActivities, intent);
13640                }
13641                if (DEBUG_SHOW_INFO) {
13642                    Log.v(TAG, "    IntentFilter:");
13643                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13644                }
13645                if (!intent.debugCheck()) {
13646                    Log.w(TAG, "==> For Activity " + a.info.name);
13647                }
13648                addFilter(intent);
13649            }
13650        }
13651
13652        public final void removeActivity(PackageParser.Activity a, String type) {
13653            mActivities.remove(a.getComponentName());
13654            if (DEBUG_SHOW_INFO) {
13655                Log.v(TAG, "  " + type + " "
13656                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13657                                : a.info.name) + ":");
13658                Log.v(TAG, "    Class=" + a.info.name);
13659            }
13660            final int NI = a.intents.size();
13661            for (int j=0; j<NI; j++) {
13662                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13663                if (DEBUG_SHOW_INFO) {
13664                    Log.v(TAG, "    IntentFilter:");
13665                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13666                }
13667                removeFilter(intent);
13668            }
13669        }
13670
13671        @Override
13672        protected boolean allowFilterResult(
13673                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13674            ActivityInfo filterAi = filter.activity.info;
13675            for (int i=dest.size()-1; i>=0; i--) {
13676                ActivityInfo destAi = dest.get(i).activityInfo;
13677                if (destAi.name == filterAi.name
13678                        && destAi.packageName == filterAi.packageName) {
13679                    return false;
13680                }
13681            }
13682            return true;
13683        }
13684
13685        @Override
13686        protected ActivityIntentInfo[] newArray(int size) {
13687            return new ActivityIntentInfo[size];
13688        }
13689
13690        @Override
13691        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13692            if (!sUserManager.exists(userId)) return true;
13693            PackageParser.Package p = filter.activity.owner;
13694            if (p != null) {
13695                PackageSetting ps = (PackageSetting)p.mExtras;
13696                if (ps != null) {
13697                    // System apps are never considered stopped for purposes of
13698                    // filtering, because there may be no way for the user to
13699                    // actually re-launch them.
13700                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13701                            && ps.getStopped(userId);
13702                }
13703            }
13704            return false;
13705        }
13706
13707        @Override
13708        protected boolean isPackageForFilter(String packageName,
13709                PackageParser.ActivityIntentInfo info) {
13710            return packageName.equals(info.activity.owner.packageName);
13711        }
13712
13713        @Override
13714        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13715                int match, int userId) {
13716            if (!sUserManager.exists(userId)) return null;
13717            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13718                return null;
13719            }
13720            final PackageParser.Activity activity = info.activity;
13721            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13722            if (ps == null) {
13723                return null;
13724            }
13725            final PackageUserState userState = ps.readUserState(userId);
13726            ActivityInfo ai =
13727                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13728            if (ai == null) {
13729                return null;
13730            }
13731            final boolean matchExplicitlyVisibleOnly =
13732                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13733            final boolean matchVisibleToInstantApp =
13734                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13735            final boolean componentVisible =
13736                    matchVisibleToInstantApp
13737                    && info.isVisibleToInstantApp()
13738                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13739            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13740            // throw out filters that aren't visible to ephemeral apps
13741            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13742                return null;
13743            }
13744            // throw out instant app filters if we're not explicitly requesting them
13745            if (!matchInstantApp && userState.instantApp) {
13746                return null;
13747            }
13748            // throw out instant app filters if updates are available; will trigger
13749            // instant app resolution
13750            if (userState.instantApp && ps.isUpdateAvailable()) {
13751                return null;
13752            }
13753            final ResolveInfo res = new ResolveInfo();
13754            res.activityInfo = ai;
13755            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13756                res.filter = info;
13757            }
13758            if (info != null) {
13759                res.handleAllWebDataURI = info.handleAllWebDataURI();
13760            }
13761            res.priority = info.getPriority();
13762            res.preferredOrder = activity.owner.mPreferredOrder;
13763            //System.out.println("Result: " + res.activityInfo.className +
13764            //                   " = " + res.priority);
13765            res.match = match;
13766            res.isDefault = info.hasDefault;
13767            res.labelRes = info.labelRes;
13768            res.nonLocalizedLabel = info.nonLocalizedLabel;
13769            if (userNeedsBadging(userId)) {
13770                res.noResourceId = true;
13771            } else {
13772                res.icon = info.icon;
13773            }
13774            res.iconResourceId = info.icon;
13775            res.system = res.activityInfo.applicationInfo.isSystemApp();
13776            res.isInstantAppAvailable = userState.instantApp;
13777            return res;
13778        }
13779
13780        @Override
13781        protected void sortResults(List<ResolveInfo> results) {
13782            Collections.sort(results, mResolvePrioritySorter);
13783        }
13784
13785        @Override
13786        protected void dumpFilter(PrintWriter out, String prefix,
13787                PackageParser.ActivityIntentInfo filter) {
13788            out.print(prefix); out.print(
13789                    Integer.toHexString(System.identityHashCode(filter.activity)));
13790                    out.print(' ');
13791                    filter.activity.printComponentShortName(out);
13792                    out.print(" filter ");
13793                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13794        }
13795
13796        @Override
13797        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13798            return filter.activity;
13799        }
13800
13801        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13802            PackageParser.Activity activity = (PackageParser.Activity)label;
13803            out.print(prefix); out.print(
13804                    Integer.toHexString(System.identityHashCode(activity)));
13805                    out.print(' ');
13806                    activity.printComponentShortName(out);
13807            if (count > 1) {
13808                out.print(" ("); out.print(count); out.print(" filters)");
13809            }
13810            out.println();
13811        }
13812
13813        // Keys are String (activity class name), values are Activity.
13814        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13815                = new ArrayMap<ComponentName, PackageParser.Activity>();
13816        private int mFlags;
13817    }
13818
13819    private final class ServiceIntentResolver
13820            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13821        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13822                boolean defaultOnly, int userId) {
13823            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13824            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13825        }
13826
13827        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13828                int userId) {
13829            if (!sUserManager.exists(userId)) return null;
13830            mFlags = flags;
13831            return super.queryIntent(intent, resolvedType,
13832                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13833                    userId);
13834        }
13835
13836        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13837                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13838            if (!sUserManager.exists(userId)) return null;
13839            if (packageServices == null) {
13840                return null;
13841            }
13842            mFlags = flags;
13843            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13844            final int N = packageServices.size();
13845            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13846                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13847
13848            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13849            for (int i = 0; i < N; ++i) {
13850                intentFilters = packageServices.get(i).intents;
13851                if (intentFilters != null && intentFilters.size() > 0) {
13852                    PackageParser.ServiceIntentInfo[] array =
13853                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13854                    intentFilters.toArray(array);
13855                    listCut.add(array);
13856                }
13857            }
13858            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13859        }
13860
13861        public final void addService(PackageParser.Service s) {
13862            mServices.put(s.getComponentName(), s);
13863            if (DEBUG_SHOW_INFO) {
13864                Log.v(TAG, "  "
13865                        + (s.info.nonLocalizedLabel != null
13866                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13867                Log.v(TAG, "    Class=" + s.info.name);
13868            }
13869            final int NI = s.intents.size();
13870            int j;
13871            for (j=0; j<NI; j++) {
13872                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13873                if (DEBUG_SHOW_INFO) {
13874                    Log.v(TAG, "    IntentFilter:");
13875                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13876                }
13877                if (!intent.debugCheck()) {
13878                    Log.w(TAG, "==> For Service " + s.info.name);
13879                }
13880                addFilter(intent);
13881            }
13882        }
13883
13884        public final void removeService(PackageParser.Service s) {
13885            mServices.remove(s.getComponentName());
13886            if (DEBUG_SHOW_INFO) {
13887                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13888                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13889                Log.v(TAG, "    Class=" + s.info.name);
13890            }
13891            final int NI = s.intents.size();
13892            int j;
13893            for (j=0; j<NI; j++) {
13894                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13895                if (DEBUG_SHOW_INFO) {
13896                    Log.v(TAG, "    IntentFilter:");
13897                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13898                }
13899                removeFilter(intent);
13900            }
13901        }
13902
13903        @Override
13904        protected boolean allowFilterResult(
13905                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13906            ServiceInfo filterSi = filter.service.info;
13907            for (int i=dest.size()-1; i>=0; i--) {
13908                ServiceInfo destAi = dest.get(i).serviceInfo;
13909                if (destAi.name == filterSi.name
13910                        && destAi.packageName == filterSi.packageName) {
13911                    return false;
13912                }
13913            }
13914            return true;
13915        }
13916
13917        @Override
13918        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13919            return new PackageParser.ServiceIntentInfo[size];
13920        }
13921
13922        @Override
13923        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13924            if (!sUserManager.exists(userId)) return true;
13925            PackageParser.Package p = filter.service.owner;
13926            if (p != null) {
13927                PackageSetting ps = (PackageSetting)p.mExtras;
13928                if (ps != null) {
13929                    // System apps are never considered stopped for purposes of
13930                    // filtering, because there may be no way for the user to
13931                    // actually re-launch them.
13932                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13933                            && ps.getStopped(userId);
13934                }
13935            }
13936            return false;
13937        }
13938
13939        @Override
13940        protected boolean isPackageForFilter(String packageName,
13941                PackageParser.ServiceIntentInfo info) {
13942            return packageName.equals(info.service.owner.packageName);
13943        }
13944
13945        @Override
13946        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13947                int match, int userId) {
13948            if (!sUserManager.exists(userId)) return null;
13949            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13950            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13951                return null;
13952            }
13953            final PackageParser.Service service = info.service;
13954            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13955            if (ps == null) {
13956                return null;
13957            }
13958            final PackageUserState userState = ps.readUserState(userId);
13959            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13960                    userState, userId);
13961            if (si == null) {
13962                return null;
13963            }
13964            final boolean matchVisibleToInstantApp =
13965                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13966            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13967            // throw out filters that aren't visible to ephemeral apps
13968            if (matchVisibleToInstantApp
13969                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13970                return null;
13971            }
13972            // throw out ephemeral filters if we're not explicitly requesting them
13973            if (!isInstantApp && userState.instantApp) {
13974                return null;
13975            }
13976            // throw out instant app filters if updates are available; will trigger
13977            // instant app resolution
13978            if (userState.instantApp && ps.isUpdateAvailable()) {
13979                return null;
13980            }
13981            final ResolveInfo res = new ResolveInfo();
13982            res.serviceInfo = si;
13983            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13984                res.filter = filter;
13985            }
13986            res.priority = info.getPriority();
13987            res.preferredOrder = service.owner.mPreferredOrder;
13988            res.match = match;
13989            res.isDefault = info.hasDefault;
13990            res.labelRes = info.labelRes;
13991            res.nonLocalizedLabel = info.nonLocalizedLabel;
13992            res.icon = info.icon;
13993            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13994            return res;
13995        }
13996
13997        @Override
13998        protected void sortResults(List<ResolveInfo> results) {
13999            Collections.sort(results, mResolvePrioritySorter);
14000        }
14001
14002        @Override
14003        protected void dumpFilter(PrintWriter out, String prefix,
14004                PackageParser.ServiceIntentInfo filter) {
14005            out.print(prefix); out.print(
14006                    Integer.toHexString(System.identityHashCode(filter.service)));
14007                    out.print(' ');
14008                    filter.service.printComponentShortName(out);
14009                    out.print(" filter ");
14010                    out.println(Integer.toHexString(System.identityHashCode(filter)));
14011        }
14012
14013        @Override
14014        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
14015            return filter.service;
14016        }
14017
14018        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14019            PackageParser.Service service = (PackageParser.Service)label;
14020            out.print(prefix); out.print(
14021                    Integer.toHexString(System.identityHashCode(service)));
14022                    out.print(' ');
14023                    service.printComponentShortName(out);
14024            if (count > 1) {
14025                out.print(" ("); out.print(count); out.print(" filters)");
14026            }
14027            out.println();
14028        }
14029
14030//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
14031//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
14032//            final List<ResolveInfo> retList = Lists.newArrayList();
14033//            while (i.hasNext()) {
14034//                final ResolveInfo resolveInfo = (ResolveInfo) i;
14035//                if (isEnabledLP(resolveInfo.serviceInfo)) {
14036//                    retList.add(resolveInfo);
14037//                }
14038//            }
14039//            return retList;
14040//        }
14041
14042        // Keys are String (activity class name), values are Activity.
14043        private final ArrayMap<ComponentName, PackageParser.Service> mServices
14044                = new ArrayMap<ComponentName, PackageParser.Service>();
14045        private int mFlags;
14046    }
14047
14048    private final class ProviderIntentResolver
14049            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
14050        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
14051                boolean defaultOnly, int userId) {
14052            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
14053            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
14054        }
14055
14056        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
14057                int userId) {
14058            if (!sUserManager.exists(userId))
14059                return null;
14060            mFlags = flags;
14061            return super.queryIntent(intent, resolvedType,
14062                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
14063                    userId);
14064        }
14065
14066        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
14067                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
14068            if (!sUserManager.exists(userId))
14069                return null;
14070            if (packageProviders == null) {
14071                return null;
14072            }
14073            mFlags = flags;
14074            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
14075            final int N = packageProviders.size();
14076            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
14077                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
14078
14079            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
14080            for (int i = 0; i < N; ++i) {
14081                intentFilters = packageProviders.get(i).intents;
14082                if (intentFilters != null && intentFilters.size() > 0) {
14083                    PackageParser.ProviderIntentInfo[] array =
14084                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
14085                    intentFilters.toArray(array);
14086                    listCut.add(array);
14087                }
14088            }
14089            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
14090        }
14091
14092        public final void addProvider(PackageParser.Provider p) {
14093            if (mProviders.containsKey(p.getComponentName())) {
14094                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
14095                return;
14096            }
14097
14098            mProviders.put(p.getComponentName(), p);
14099            if (DEBUG_SHOW_INFO) {
14100                Log.v(TAG, "  "
14101                        + (p.info.nonLocalizedLabel != null
14102                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
14103                Log.v(TAG, "    Class=" + p.info.name);
14104            }
14105            final int NI = p.intents.size();
14106            int j;
14107            for (j = 0; j < NI; j++) {
14108                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14109                if (DEBUG_SHOW_INFO) {
14110                    Log.v(TAG, "    IntentFilter:");
14111                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14112                }
14113                if (!intent.debugCheck()) {
14114                    Log.w(TAG, "==> For Provider " + p.info.name);
14115                }
14116                addFilter(intent);
14117            }
14118        }
14119
14120        public final void removeProvider(PackageParser.Provider p) {
14121            mProviders.remove(p.getComponentName());
14122            if (DEBUG_SHOW_INFO) {
14123                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
14124                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
14125                Log.v(TAG, "    Class=" + p.info.name);
14126            }
14127            final int NI = p.intents.size();
14128            int j;
14129            for (j = 0; j < NI; j++) {
14130                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14131                if (DEBUG_SHOW_INFO) {
14132                    Log.v(TAG, "    IntentFilter:");
14133                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14134                }
14135                removeFilter(intent);
14136            }
14137        }
14138
14139        @Override
14140        protected boolean allowFilterResult(
14141                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
14142            ProviderInfo filterPi = filter.provider.info;
14143            for (int i = dest.size() - 1; i >= 0; i--) {
14144                ProviderInfo destPi = dest.get(i).providerInfo;
14145                if (destPi.name == filterPi.name
14146                        && destPi.packageName == filterPi.packageName) {
14147                    return false;
14148                }
14149            }
14150            return true;
14151        }
14152
14153        @Override
14154        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
14155            return new PackageParser.ProviderIntentInfo[size];
14156        }
14157
14158        @Override
14159        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
14160            if (!sUserManager.exists(userId))
14161                return true;
14162            PackageParser.Package p = filter.provider.owner;
14163            if (p != null) {
14164                PackageSetting ps = (PackageSetting) p.mExtras;
14165                if (ps != null) {
14166                    // System apps are never considered stopped for purposes of
14167                    // filtering, because there may be no way for the user to
14168                    // actually re-launch them.
14169                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14170                            && ps.getStopped(userId);
14171                }
14172            }
14173            return false;
14174        }
14175
14176        @Override
14177        protected boolean isPackageForFilter(String packageName,
14178                PackageParser.ProviderIntentInfo info) {
14179            return packageName.equals(info.provider.owner.packageName);
14180        }
14181
14182        @Override
14183        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
14184                int match, int userId) {
14185            if (!sUserManager.exists(userId))
14186                return null;
14187            final PackageParser.ProviderIntentInfo info = filter;
14188            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
14189                return null;
14190            }
14191            final PackageParser.Provider provider = info.provider;
14192            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
14193            if (ps == null) {
14194                return null;
14195            }
14196            final PackageUserState userState = ps.readUserState(userId);
14197            final boolean matchVisibleToInstantApp =
14198                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14199            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14200            // throw out filters that aren't visible to instant applications
14201            if (matchVisibleToInstantApp
14202                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14203                return null;
14204            }
14205            // throw out instant application filters if we're not explicitly requesting them
14206            if (!isInstantApp && userState.instantApp) {
14207                return null;
14208            }
14209            // throw out instant application filters if updates are available; will trigger
14210            // instant application resolution
14211            if (userState.instantApp && ps.isUpdateAvailable()) {
14212                return null;
14213            }
14214            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
14215                    userState, userId);
14216            if (pi == null) {
14217                return null;
14218            }
14219            final ResolveInfo res = new ResolveInfo();
14220            res.providerInfo = pi;
14221            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
14222                res.filter = filter;
14223            }
14224            res.priority = info.getPriority();
14225            res.preferredOrder = provider.owner.mPreferredOrder;
14226            res.match = match;
14227            res.isDefault = info.hasDefault;
14228            res.labelRes = info.labelRes;
14229            res.nonLocalizedLabel = info.nonLocalizedLabel;
14230            res.icon = info.icon;
14231            res.system = res.providerInfo.applicationInfo.isSystemApp();
14232            return res;
14233        }
14234
14235        @Override
14236        protected void sortResults(List<ResolveInfo> results) {
14237            Collections.sort(results, mResolvePrioritySorter);
14238        }
14239
14240        @Override
14241        protected void dumpFilter(PrintWriter out, String prefix,
14242                PackageParser.ProviderIntentInfo filter) {
14243            out.print(prefix);
14244            out.print(
14245                    Integer.toHexString(System.identityHashCode(filter.provider)));
14246            out.print(' ');
14247            filter.provider.printComponentShortName(out);
14248            out.print(" filter ");
14249            out.println(Integer.toHexString(System.identityHashCode(filter)));
14250        }
14251
14252        @Override
14253        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
14254            return filter.provider;
14255        }
14256
14257        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14258            PackageParser.Provider provider = (PackageParser.Provider)label;
14259            out.print(prefix); out.print(
14260                    Integer.toHexString(System.identityHashCode(provider)));
14261                    out.print(' ');
14262                    provider.printComponentShortName(out);
14263            if (count > 1) {
14264                out.print(" ("); out.print(count); out.print(" filters)");
14265            }
14266            out.println();
14267        }
14268
14269        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
14270                = new ArrayMap<ComponentName, PackageParser.Provider>();
14271        private int mFlags;
14272    }
14273
14274    static final class EphemeralIntentResolver
14275            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
14276        /**
14277         * The result that has the highest defined order. Ordering applies on a
14278         * per-package basis. Mapping is from package name to Pair of order and
14279         * EphemeralResolveInfo.
14280         * <p>
14281         * NOTE: This is implemented as a field variable for convenience and efficiency.
14282         * By having a field variable, we're able to track filter ordering as soon as
14283         * a non-zero order is defined. Otherwise, multiple loops across the result set
14284         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
14285         * this needs to be contained entirely within {@link #filterResults}.
14286         */
14287        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
14288
14289        @Override
14290        protected AuxiliaryResolveInfo[] newArray(int size) {
14291            return new AuxiliaryResolveInfo[size];
14292        }
14293
14294        @Override
14295        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
14296            return true;
14297        }
14298
14299        @Override
14300        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
14301                int userId) {
14302            if (!sUserManager.exists(userId)) {
14303                return null;
14304            }
14305            final String packageName = responseObj.resolveInfo.getPackageName();
14306            final Integer order = responseObj.getOrder();
14307            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
14308                    mOrderResult.get(packageName);
14309            // ordering is enabled and this item's order isn't high enough
14310            if (lastOrderResult != null && lastOrderResult.first >= order) {
14311                return null;
14312            }
14313            final InstantAppResolveInfo res = responseObj.resolveInfo;
14314            if (order > 0) {
14315                // non-zero order, enable ordering
14316                mOrderResult.put(packageName, new Pair<>(order, res));
14317            }
14318            return responseObj;
14319        }
14320
14321        @Override
14322        protected void filterResults(List<AuxiliaryResolveInfo> results) {
14323            // only do work if ordering is enabled [most of the time it won't be]
14324            if (mOrderResult.size() == 0) {
14325                return;
14326            }
14327            int resultSize = results.size();
14328            for (int i = 0; i < resultSize; i++) {
14329                final InstantAppResolveInfo info = results.get(i).resolveInfo;
14330                final String packageName = info.getPackageName();
14331                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
14332                if (savedInfo == null) {
14333                    // package doesn't having ordering
14334                    continue;
14335                }
14336                if (savedInfo.second == info) {
14337                    // circled back to the highest ordered item; remove from order list
14338                    mOrderResult.remove(savedInfo);
14339                    if (mOrderResult.size() == 0) {
14340                        // no more ordered items
14341                        break;
14342                    }
14343                    continue;
14344                }
14345                // item has a worse order, remove it from the result list
14346                results.remove(i);
14347                resultSize--;
14348                i--;
14349            }
14350        }
14351    }
14352
14353    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14354            new Comparator<ResolveInfo>() {
14355        public int compare(ResolveInfo r1, ResolveInfo r2) {
14356            int v1 = r1.priority;
14357            int v2 = r2.priority;
14358            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14359            if (v1 != v2) {
14360                return (v1 > v2) ? -1 : 1;
14361            }
14362            v1 = r1.preferredOrder;
14363            v2 = r2.preferredOrder;
14364            if (v1 != v2) {
14365                return (v1 > v2) ? -1 : 1;
14366            }
14367            if (r1.isDefault != r2.isDefault) {
14368                return r1.isDefault ? -1 : 1;
14369            }
14370            v1 = r1.match;
14371            v2 = r2.match;
14372            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14373            if (v1 != v2) {
14374                return (v1 > v2) ? -1 : 1;
14375            }
14376            if (r1.system != r2.system) {
14377                return r1.system ? -1 : 1;
14378            }
14379            if (r1.activityInfo != null) {
14380                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14381            }
14382            if (r1.serviceInfo != null) {
14383                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14384            }
14385            if (r1.providerInfo != null) {
14386                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14387            }
14388            return 0;
14389        }
14390    };
14391
14392    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14393            new Comparator<ProviderInfo>() {
14394        public int compare(ProviderInfo p1, ProviderInfo p2) {
14395            final int v1 = p1.initOrder;
14396            final int v2 = p2.initOrder;
14397            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14398        }
14399    };
14400
14401    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14402            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14403            final int[] userIds) {
14404        mHandler.post(new Runnable() {
14405            @Override
14406            public void run() {
14407                try {
14408                    final IActivityManager am = ActivityManager.getService();
14409                    if (am == null) return;
14410                    final int[] resolvedUserIds;
14411                    if (userIds == null) {
14412                        resolvedUserIds = am.getRunningUserIds();
14413                    } else {
14414                        resolvedUserIds = userIds;
14415                    }
14416                    for (int id : resolvedUserIds) {
14417                        final Intent intent = new Intent(action,
14418                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14419                        if (extras != null) {
14420                            intent.putExtras(extras);
14421                        }
14422                        if (targetPkg != null) {
14423                            intent.setPackage(targetPkg);
14424                        }
14425                        // Modify the UID when posting to other users
14426                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14427                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14428                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14429                            intent.putExtra(Intent.EXTRA_UID, uid);
14430                        }
14431                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14432                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14433                        if (DEBUG_BROADCASTS) {
14434                            RuntimeException here = new RuntimeException("here");
14435                            here.fillInStackTrace();
14436                            Slog.d(TAG, "Sending to user " + id + ": "
14437                                    + intent.toShortString(false, true, false, false)
14438                                    + " " + intent.getExtras(), here);
14439                        }
14440                        am.broadcastIntent(null, intent, null, finishedReceiver,
14441                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14442                                null, finishedReceiver != null, false, id);
14443                    }
14444                } catch (RemoteException ex) {
14445                }
14446            }
14447        });
14448    }
14449
14450    /**
14451     * Check if the external storage media is available. This is true if there
14452     * is a mounted external storage medium or if the external storage is
14453     * emulated.
14454     */
14455    private boolean isExternalMediaAvailable() {
14456        return mMediaMounted || Environment.isExternalStorageEmulated();
14457    }
14458
14459    @Override
14460    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14461        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14462            return null;
14463        }
14464        // writer
14465        synchronized (mPackages) {
14466            if (!isExternalMediaAvailable()) {
14467                // If the external storage is no longer mounted at this point,
14468                // the caller may not have been able to delete all of this
14469                // packages files and can not delete any more.  Bail.
14470                return null;
14471            }
14472            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14473            if (lastPackage != null) {
14474                pkgs.remove(lastPackage);
14475            }
14476            if (pkgs.size() > 0) {
14477                return pkgs.get(0);
14478            }
14479        }
14480        return null;
14481    }
14482
14483    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14484        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14485                userId, andCode ? 1 : 0, packageName);
14486        if (mSystemReady) {
14487            msg.sendToTarget();
14488        } else {
14489            if (mPostSystemReadyMessages == null) {
14490                mPostSystemReadyMessages = new ArrayList<>();
14491            }
14492            mPostSystemReadyMessages.add(msg);
14493        }
14494    }
14495
14496    void startCleaningPackages() {
14497        // reader
14498        if (!isExternalMediaAvailable()) {
14499            return;
14500        }
14501        synchronized (mPackages) {
14502            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14503                return;
14504            }
14505        }
14506        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14507        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14508        IActivityManager am = ActivityManager.getService();
14509        if (am != null) {
14510            int dcsUid = -1;
14511            synchronized (mPackages) {
14512                if (!mDefaultContainerWhitelisted) {
14513                    mDefaultContainerWhitelisted = true;
14514                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14515                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14516                }
14517            }
14518            try {
14519                if (dcsUid > 0) {
14520                    am.backgroundWhitelistUid(dcsUid);
14521                }
14522                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14523                        UserHandle.USER_SYSTEM);
14524            } catch (RemoteException e) {
14525            }
14526        }
14527    }
14528
14529    @Override
14530    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14531            int installFlags, String installerPackageName, int userId) {
14532        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14533
14534        final int callingUid = Binder.getCallingUid();
14535        enforceCrossUserPermission(callingUid, userId,
14536                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14537
14538        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14539            try {
14540                if (observer != null) {
14541                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14542                }
14543            } catch (RemoteException re) {
14544            }
14545            return;
14546        }
14547
14548        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14549            installFlags |= PackageManager.INSTALL_FROM_ADB;
14550
14551        } else {
14552            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14553            // about installerPackageName.
14554
14555            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14556            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14557        }
14558
14559        UserHandle user;
14560        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14561            user = UserHandle.ALL;
14562        } else {
14563            user = new UserHandle(userId);
14564        }
14565
14566        // Only system components can circumvent runtime permissions when installing.
14567        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14568                && mContext.checkCallingOrSelfPermission(Manifest.permission
14569                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14570            throw new SecurityException("You need the "
14571                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14572                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14573        }
14574
14575        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14576                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14577            throw new IllegalArgumentException(
14578                    "New installs into ASEC containers no longer supported");
14579        }
14580
14581        final File originFile = new File(originPath);
14582        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14583
14584        final Message msg = mHandler.obtainMessage(INIT_COPY);
14585        final VerificationInfo verificationInfo = new VerificationInfo(
14586                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14587        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14588                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14589                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14590                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14591        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14592        msg.obj = params;
14593
14594        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14595                System.identityHashCode(msg.obj));
14596        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14597                System.identityHashCode(msg.obj));
14598
14599        mHandler.sendMessage(msg);
14600    }
14601
14602
14603    /**
14604     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14605     * it is acting on behalf on an enterprise or the user).
14606     *
14607     * Note that the ordering of the conditionals in this method is important. The checks we perform
14608     * are as follows, in this order:
14609     *
14610     * 1) If the install is being performed by a system app, we can trust the app to have set the
14611     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14612     *    what it is.
14613     * 2) If the install is being performed by a device or profile owner app, the install reason
14614     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14615     *    set the install reason correctly. If the app targets an older SDK version where install
14616     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14617     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14618     * 3) In all other cases, the install is being performed by a regular app that is neither part
14619     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14620     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14621     *    set to enterprise policy and if so, change it to unknown instead.
14622     */
14623    private int fixUpInstallReason(String installerPackageName, int installerUid,
14624            int installReason) {
14625        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14626                == PERMISSION_GRANTED) {
14627            // If the install is being performed by a system app, we trust that app to have set the
14628            // install reason correctly.
14629            return installReason;
14630        }
14631
14632        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14633            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14634        if (dpm != null) {
14635            ComponentName owner = null;
14636            try {
14637                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14638                if (owner == null) {
14639                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14640                }
14641            } catch (RemoteException e) {
14642            }
14643            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14644                // If the install is being performed by a device or profile owner, the install
14645                // reason should be enterprise policy.
14646                return PackageManager.INSTALL_REASON_POLICY;
14647            }
14648        }
14649
14650        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14651            // If the install is being performed by a regular app (i.e. neither system app nor
14652            // device or profile owner), we have no reason to believe that the app is acting on
14653            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14654            // change it to unknown instead.
14655            return PackageManager.INSTALL_REASON_UNKNOWN;
14656        }
14657
14658        // If the install is being performed by a regular app and the install reason was set to any
14659        // value but enterprise policy, leave the install reason unchanged.
14660        return installReason;
14661    }
14662
14663    void installStage(String packageName, File stagedDir, String stagedCid,
14664            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14665            String installerPackageName, int installerUid, UserHandle user,
14666            Certificate[][] certificates) {
14667        if (DEBUG_EPHEMERAL) {
14668            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14669                Slog.d(TAG, "Ephemeral install of " + packageName);
14670            }
14671        }
14672        final VerificationInfo verificationInfo = new VerificationInfo(
14673                sessionParams.originatingUri, sessionParams.referrerUri,
14674                sessionParams.originatingUid, installerUid);
14675
14676        final OriginInfo origin;
14677        if (stagedDir != null) {
14678            origin = OriginInfo.fromStagedFile(stagedDir);
14679        } else {
14680            origin = OriginInfo.fromStagedContainer(stagedCid);
14681        }
14682
14683        final Message msg = mHandler.obtainMessage(INIT_COPY);
14684        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14685                sessionParams.installReason);
14686        final InstallParams params = new InstallParams(origin, null, observer,
14687                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14688                verificationInfo, user, sessionParams.abiOverride,
14689                sessionParams.grantedRuntimePermissions, certificates, installReason);
14690        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14691        msg.obj = params;
14692
14693        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14694                System.identityHashCode(msg.obj));
14695        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14696                System.identityHashCode(msg.obj));
14697
14698        mHandler.sendMessage(msg);
14699    }
14700
14701    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14702            int userId) {
14703        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14704        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
14705                false /*startReceiver*/, pkgSetting.appId, userId);
14706
14707        // Send a session commit broadcast
14708        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14709        info.installReason = pkgSetting.getInstallReason(userId);
14710        info.appPackageName = packageName;
14711        sendSessionCommitBroadcast(info, userId);
14712    }
14713
14714    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
14715            boolean includeStopped, int appId, int... userIds) {
14716        if (ArrayUtils.isEmpty(userIds)) {
14717            return;
14718        }
14719        Bundle extras = new Bundle(1);
14720        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14721        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14722
14723        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14724                packageName, extras, 0, null, null, userIds);
14725        if (sendBootCompleted) {
14726            mHandler.post(() -> {
14727                        for (int userId : userIds) {
14728                            sendBootCompletedBroadcastToSystemApp(
14729                                    packageName, includeStopped, userId);
14730                        }
14731                    }
14732            );
14733        }
14734    }
14735
14736    /**
14737     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14738     * automatically without needing an explicit launch.
14739     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14740     */
14741    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
14742            int userId) {
14743        // If user is not running, the app didn't miss any broadcast
14744        if (!mUserManagerInternal.isUserRunning(userId)) {
14745            return;
14746        }
14747        final IActivityManager am = ActivityManager.getService();
14748        try {
14749            // Deliver LOCKED_BOOT_COMPLETED first
14750            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14751                    .setPackage(packageName);
14752            if (includeStopped) {
14753                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14754            }
14755            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14756            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14757                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14758
14759            // Deliver BOOT_COMPLETED only if user is unlocked
14760            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14761                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14762                if (includeStopped) {
14763                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14764                }
14765                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14766                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14767            }
14768        } catch (RemoteException e) {
14769            throw e.rethrowFromSystemServer();
14770        }
14771    }
14772
14773    @Override
14774    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14775            int userId) {
14776        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14777        PackageSetting pkgSetting;
14778        final int callingUid = Binder.getCallingUid();
14779        enforceCrossUserPermission(callingUid, userId,
14780                true /* requireFullPermission */, true /* checkShell */,
14781                "setApplicationHiddenSetting for user " + userId);
14782
14783        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14784            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14785            return false;
14786        }
14787
14788        long callingId = Binder.clearCallingIdentity();
14789        try {
14790            boolean sendAdded = false;
14791            boolean sendRemoved = false;
14792            // writer
14793            synchronized (mPackages) {
14794                pkgSetting = mSettings.mPackages.get(packageName);
14795                if (pkgSetting == null) {
14796                    return false;
14797                }
14798                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14799                    return false;
14800                }
14801                // Do not allow "android" is being disabled
14802                if ("android".equals(packageName)) {
14803                    Slog.w(TAG, "Cannot hide package: android");
14804                    return false;
14805                }
14806                // Cannot hide static shared libs as they are considered
14807                // a part of the using app (emulating static linking). Also
14808                // static libs are installed always on internal storage.
14809                PackageParser.Package pkg = mPackages.get(packageName);
14810                if (pkg != null && pkg.staticSharedLibName != null) {
14811                    Slog.w(TAG, "Cannot hide package: " + packageName
14812                            + " providing static shared library: "
14813                            + pkg.staticSharedLibName);
14814                    return false;
14815                }
14816                // Only allow protected packages to hide themselves.
14817                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14818                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14819                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14820                    return false;
14821                }
14822
14823                if (pkgSetting.getHidden(userId) != hidden) {
14824                    pkgSetting.setHidden(hidden, userId);
14825                    mSettings.writePackageRestrictionsLPr(userId);
14826                    if (hidden) {
14827                        sendRemoved = true;
14828                    } else {
14829                        sendAdded = true;
14830                    }
14831                }
14832            }
14833            if (sendAdded) {
14834                sendPackageAddedForUser(packageName, pkgSetting, userId);
14835                return true;
14836            }
14837            if (sendRemoved) {
14838                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14839                        "hiding pkg");
14840                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14841                return true;
14842            }
14843        } finally {
14844            Binder.restoreCallingIdentity(callingId);
14845        }
14846        return false;
14847    }
14848
14849    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14850            int userId) {
14851        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14852        info.removedPackage = packageName;
14853        info.installerPackageName = pkgSetting.installerPackageName;
14854        info.removedUsers = new int[] {userId};
14855        info.broadcastUsers = new int[] {userId};
14856        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14857        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14858    }
14859
14860    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14861        if (pkgList.length > 0) {
14862            Bundle extras = new Bundle(1);
14863            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14864
14865            sendPackageBroadcast(
14866                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14867                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14868                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14869                    new int[] {userId});
14870        }
14871    }
14872
14873    /**
14874     * Returns true if application is not found or there was an error. Otherwise it returns
14875     * the hidden state of the package for the given user.
14876     */
14877    @Override
14878    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14879        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14880        final int callingUid = Binder.getCallingUid();
14881        enforceCrossUserPermission(callingUid, userId,
14882                true /* requireFullPermission */, false /* checkShell */,
14883                "getApplicationHidden for user " + userId);
14884        PackageSetting ps;
14885        long callingId = Binder.clearCallingIdentity();
14886        try {
14887            // writer
14888            synchronized (mPackages) {
14889                ps = mSettings.mPackages.get(packageName);
14890                if (ps == null) {
14891                    return true;
14892                }
14893                if (filterAppAccessLPr(ps, callingUid, userId)) {
14894                    return true;
14895                }
14896                return ps.getHidden(userId);
14897            }
14898        } finally {
14899            Binder.restoreCallingIdentity(callingId);
14900        }
14901    }
14902
14903    /**
14904     * @hide
14905     */
14906    @Override
14907    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14908            int installReason) {
14909        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14910                null);
14911        PackageSetting pkgSetting;
14912        final int callingUid = Binder.getCallingUid();
14913        enforceCrossUserPermission(callingUid, userId,
14914                true /* requireFullPermission */, true /* checkShell */,
14915                "installExistingPackage for user " + userId);
14916        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14917            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14918        }
14919
14920        long callingId = Binder.clearCallingIdentity();
14921        try {
14922            boolean installed = false;
14923            final boolean instantApp =
14924                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14925            final boolean fullApp =
14926                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14927
14928            // writer
14929            synchronized (mPackages) {
14930                pkgSetting = mSettings.mPackages.get(packageName);
14931                if (pkgSetting == null) {
14932                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14933                }
14934                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14935                    // only allow the existing package to be used if it's installed as a full
14936                    // application for at least one user
14937                    boolean installAllowed = false;
14938                    for (int checkUserId : sUserManager.getUserIds()) {
14939                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14940                        if (installAllowed) {
14941                            break;
14942                        }
14943                    }
14944                    if (!installAllowed) {
14945                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14946                    }
14947                }
14948                if (!pkgSetting.getInstalled(userId)) {
14949                    pkgSetting.setInstalled(true, userId);
14950                    pkgSetting.setHidden(false, userId);
14951                    pkgSetting.setInstallReason(installReason, userId);
14952                    mSettings.writePackageRestrictionsLPr(userId);
14953                    mSettings.writeKernelMappingLPr(pkgSetting);
14954                    installed = true;
14955                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14956                    // upgrade app from instant to full; we don't allow app downgrade
14957                    installed = true;
14958                }
14959                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14960            }
14961
14962            if (installed) {
14963                if (pkgSetting.pkg != null) {
14964                    synchronized (mInstallLock) {
14965                        // We don't need to freeze for a brand new install
14966                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14967                    }
14968                }
14969                sendPackageAddedForUser(packageName, pkgSetting, userId);
14970                synchronized (mPackages) {
14971                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14972                }
14973            }
14974        } finally {
14975            Binder.restoreCallingIdentity(callingId);
14976        }
14977
14978        return PackageManager.INSTALL_SUCCEEDED;
14979    }
14980
14981    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14982            boolean instantApp, boolean fullApp) {
14983        // no state specified; do nothing
14984        if (!instantApp && !fullApp) {
14985            return;
14986        }
14987        if (userId != UserHandle.USER_ALL) {
14988            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14989                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14990            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14991                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14992            }
14993        } else {
14994            for (int currentUserId : sUserManager.getUserIds()) {
14995                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14996                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14997                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14998                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14999                }
15000            }
15001        }
15002    }
15003
15004    boolean isUserRestricted(int userId, String restrictionKey) {
15005        Bundle restrictions = sUserManager.getUserRestrictions(userId);
15006        if (restrictions.getBoolean(restrictionKey, false)) {
15007            Log.w(TAG, "User is restricted: " + restrictionKey);
15008            return true;
15009        }
15010        return false;
15011    }
15012
15013    @Override
15014    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
15015            int userId) {
15016        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
15017        final int callingUid = Binder.getCallingUid();
15018        enforceCrossUserPermission(callingUid, userId,
15019                true /* requireFullPermission */, true /* checkShell */,
15020                "setPackagesSuspended for user " + userId);
15021
15022        if (ArrayUtils.isEmpty(packageNames)) {
15023            return packageNames;
15024        }
15025
15026        // List of package names for whom the suspended state has changed.
15027        List<String> changedPackages = new ArrayList<>(packageNames.length);
15028        // List of package names for whom the suspended state is not set as requested in this
15029        // method.
15030        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
15031        long callingId = Binder.clearCallingIdentity();
15032        try {
15033            for (int i = 0; i < packageNames.length; i++) {
15034                String packageName = packageNames[i];
15035                boolean changed = false;
15036                final int appId;
15037                synchronized (mPackages) {
15038                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
15039                    if (pkgSetting == null
15040                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
15041                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
15042                                + "\". Skipping suspending/un-suspending.");
15043                        unactionedPackages.add(packageName);
15044                        continue;
15045                    }
15046                    appId = pkgSetting.appId;
15047                    if (pkgSetting.getSuspended(userId) != suspended) {
15048                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
15049                            unactionedPackages.add(packageName);
15050                            continue;
15051                        }
15052                        pkgSetting.setSuspended(suspended, userId);
15053                        mSettings.writePackageRestrictionsLPr(userId);
15054                        changed = true;
15055                        changedPackages.add(packageName);
15056                    }
15057                }
15058
15059                if (changed && suspended) {
15060                    killApplication(packageName, UserHandle.getUid(userId, appId),
15061                            "suspending package");
15062                }
15063            }
15064        } finally {
15065            Binder.restoreCallingIdentity(callingId);
15066        }
15067
15068        if (!changedPackages.isEmpty()) {
15069            sendPackagesSuspendedForUser(changedPackages.toArray(
15070                    new String[changedPackages.size()]), userId, suspended);
15071        }
15072
15073        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
15074    }
15075
15076    @Override
15077    public boolean isPackageSuspendedForUser(String packageName, int userId) {
15078        final int callingUid = Binder.getCallingUid();
15079        enforceCrossUserPermission(callingUid, userId,
15080                true /* requireFullPermission */, false /* checkShell */,
15081                "isPackageSuspendedForUser for user " + userId);
15082        synchronized (mPackages) {
15083            final PackageSetting ps = mSettings.mPackages.get(packageName);
15084            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
15085                throw new IllegalArgumentException("Unknown target package: " + packageName);
15086            }
15087            return ps.getSuspended(userId);
15088        }
15089    }
15090
15091    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
15092        if (isPackageDeviceAdmin(packageName, userId)) {
15093            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15094                    + "\": has an active device admin");
15095            return false;
15096        }
15097
15098        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
15099        if (packageName.equals(activeLauncherPackageName)) {
15100            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15101                    + "\": contains the active launcher");
15102            return false;
15103        }
15104
15105        if (packageName.equals(mRequiredInstallerPackage)) {
15106            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15107                    + "\": required for package installation");
15108            return false;
15109        }
15110
15111        if (packageName.equals(mRequiredUninstallerPackage)) {
15112            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15113                    + "\": required for package uninstallation");
15114            return false;
15115        }
15116
15117        if (packageName.equals(mRequiredVerifierPackage)) {
15118            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15119                    + "\": required for package verification");
15120            return false;
15121        }
15122
15123        if (packageName.equals(getDefaultDialerPackageName(userId))) {
15124            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15125                    + "\": is the default dialer");
15126            return false;
15127        }
15128
15129        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
15130            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15131                    + "\": protected package");
15132            return false;
15133        }
15134
15135        // Cannot suspend static shared libs as they are considered
15136        // a part of the using app (emulating static linking). Also
15137        // static libs are installed always on internal storage.
15138        PackageParser.Package pkg = mPackages.get(packageName);
15139        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
15140            Slog.w(TAG, "Cannot suspend package: " + packageName
15141                    + " providing static shared library: "
15142                    + pkg.staticSharedLibName);
15143            return false;
15144        }
15145
15146        return true;
15147    }
15148
15149    private String getActiveLauncherPackageName(int userId) {
15150        Intent intent = new Intent(Intent.ACTION_MAIN);
15151        intent.addCategory(Intent.CATEGORY_HOME);
15152        ResolveInfo resolveInfo = resolveIntent(
15153                intent,
15154                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
15155                PackageManager.MATCH_DEFAULT_ONLY,
15156                userId);
15157
15158        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
15159    }
15160
15161    private String getDefaultDialerPackageName(int userId) {
15162        synchronized (mPackages) {
15163            return mSettings.getDefaultDialerPackageNameLPw(userId);
15164        }
15165    }
15166
15167    @Override
15168    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
15169        mContext.enforceCallingOrSelfPermission(
15170                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15171                "Only package verification agents can verify applications");
15172
15173        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15174        final PackageVerificationResponse response = new PackageVerificationResponse(
15175                verificationCode, Binder.getCallingUid());
15176        msg.arg1 = id;
15177        msg.obj = response;
15178        mHandler.sendMessage(msg);
15179    }
15180
15181    @Override
15182    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
15183            long millisecondsToDelay) {
15184        mContext.enforceCallingOrSelfPermission(
15185                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15186                "Only package verification agents can extend verification timeouts");
15187
15188        final PackageVerificationState state = mPendingVerification.get(id);
15189        final PackageVerificationResponse response = new PackageVerificationResponse(
15190                verificationCodeAtTimeout, Binder.getCallingUid());
15191
15192        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
15193            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
15194        }
15195        if (millisecondsToDelay < 0) {
15196            millisecondsToDelay = 0;
15197        }
15198        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
15199                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
15200            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
15201        }
15202
15203        if ((state != null) && !state.timeoutExtended()) {
15204            state.extendTimeout();
15205
15206            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15207            msg.arg1 = id;
15208            msg.obj = response;
15209            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
15210        }
15211    }
15212
15213    private void broadcastPackageVerified(int verificationId, Uri packageUri,
15214            int verificationCode, UserHandle user) {
15215        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
15216        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
15217        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15218        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15219        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
15220
15221        mContext.sendBroadcastAsUser(intent, user,
15222                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
15223    }
15224
15225    private ComponentName matchComponentForVerifier(String packageName,
15226            List<ResolveInfo> receivers) {
15227        ActivityInfo targetReceiver = null;
15228
15229        final int NR = receivers.size();
15230        for (int i = 0; i < NR; i++) {
15231            final ResolveInfo info = receivers.get(i);
15232            if (info.activityInfo == null) {
15233                continue;
15234            }
15235
15236            if (packageName.equals(info.activityInfo.packageName)) {
15237                targetReceiver = info.activityInfo;
15238                break;
15239            }
15240        }
15241
15242        if (targetReceiver == null) {
15243            return null;
15244        }
15245
15246        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
15247    }
15248
15249    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
15250            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
15251        if (pkgInfo.verifiers.length == 0) {
15252            return null;
15253        }
15254
15255        final int N = pkgInfo.verifiers.length;
15256        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
15257        for (int i = 0; i < N; i++) {
15258            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
15259
15260            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
15261                    receivers);
15262            if (comp == null) {
15263                continue;
15264            }
15265
15266            final int verifierUid = getUidForVerifier(verifierInfo);
15267            if (verifierUid == -1) {
15268                continue;
15269            }
15270
15271            if (DEBUG_VERIFY) {
15272                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
15273                        + " with the correct signature");
15274            }
15275            sufficientVerifiers.add(comp);
15276            verificationState.addSufficientVerifier(verifierUid);
15277        }
15278
15279        return sufficientVerifiers;
15280    }
15281
15282    private int getUidForVerifier(VerifierInfo verifierInfo) {
15283        synchronized (mPackages) {
15284            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
15285            if (pkg == null) {
15286                return -1;
15287            } else if (pkg.mSignatures.length != 1) {
15288                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15289                        + " has more than one signature; ignoring");
15290                return -1;
15291            }
15292
15293            /*
15294             * If the public key of the package's signature does not match
15295             * our expected public key, then this is a different package and
15296             * we should skip.
15297             */
15298
15299            final byte[] expectedPublicKey;
15300            try {
15301                final Signature verifierSig = pkg.mSignatures[0];
15302                final PublicKey publicKey = verifierSig.getPublicKey();
15303                expectedPublicKey = publicKey.getEncoded();
15304            } catch (CertificateException e) {
15305                return -1;
15306            }
15307
15308            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
15309
15310            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
15311                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15312                        + " does not have the expected public key; ignoring");
15313                return -1;
15314            }
15315
15316            return pkg.applicationInfo.uid;
15317        }
15318    }
15319
15320    @Override
15321    public void finishPackageInstall(int token, boolean didLaunch) {
15322        enforceSystemOrRoot("Only the system is allowed to finish installs");
15323
15324        if (DEBUG_INSTALL) {
15325            Slog.v(TAG, "BM finishing package install for " + token);
15326        }
15327        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15328
15329        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
15330        mHandler.sendMessage(msg);
15331    }
15332
15333    /**
15334     * Get the verification agent timeout.  Used for both the APK verifier and the
15335     * intent filter verifier.
15336     *
15337     * @return verification timeout in milliseconds
15338     */
15339    private long getVerificationTimeout() {
15340        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
15341                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
15342                DEFAULT_VERIFICATION_TIMEOUT);
15343    }
15344
15345    /**
15346     * Get the default verification agent response code.
15347     *
15348     * @return default verification response code
15349     */
15350    private int getDefaultVerificationResponse(UserHandle user) {
15351        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
15352            return PackageManager.VERIFICATION_REJECT;
15353        }
15354        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15355                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15356                DEFAULT_VERIFICATION_RESPONSE);
15357    }
15358
15359    /**
15360     * Check whether or not package verification has been enabled.
15361     *
15362     * @return true if verification should be performed
15363     */
15364    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15365        if (!DEFAULT_VERIFY_ENABLE) {
15366            return false;
15367        }
15368
15369        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15370
15371        // Check if installing from ADB
15372        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15373            // Do not run verification in a test harness environment
15374            if (ActivityManager.isRunningInTestHarness()) {
15375                return false;
15376            }
15377            if (ensureVerifyAppsEnabled) {
15378                return true;
15379            }
15380            // Check if the developer does not want package verification for ADB installs
15381            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15382                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15383                return false;
15384            }
15385        } else {
15386            // only when not installed from ADB, skip verification for instant apps when
15387            // the installer and verifier are the same.
15388            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15389                if (mInstantAppInstallerActivity != null
15390                        && mInstantAppInstallerActivity.packageName.equals(
15391                                mRequiredVerifierPackage)) {
15392                    try {
15393                        mContext.getSystemService(AppOpsManager.class)
15394                                .checkPackage(installerUid, mRequiredVerifierPackage);
15395                        if (DEBUG_VERIFY) {
15396                            Slog.i(TAG, "disable verification for instant app");
15397                        }
15398                        return false;
15399                    } catch (SecurityException ignore) { }
15400                }
15401            }
15402        }
15403
15404        if (ensureVerifyAppsEnabled) {
15405            return true;
15406        }
15407
15408        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15409                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15410    }
15411
15412    @Override
15413    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15414            throws RemoteException {
15415        mContext.enforceCallingOrSelfPermission(
15416                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15417                "Only intentfilter verification agents can verify applications");
15418
15419        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15420        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15421                Binder.getCallingUid(), verificationCode, failedDomains);
15422        msg.arg1 = id;
15423        msg.obj = response;
15424        mHandler.sendMessage(msg);
15425    }
15426
15427    @Override
15428    public int getIntentVerificationStatus(String packageName, int userId) {
15429        final int callingUid = Binder.getCallingUid();
15430        if (UserHandle.getUserId(callingUid) != userId) {
15431            mContext.enforceCallingOrSelfPermission(
15432                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15433                    "getIntentVerificationStatus" + userId);
15434        }
15435        if (getInstantAppPackageName(callingUid) != null) {
15436            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15437        }
15438        synchronized (mPackages) {
15439            final PackageSetting ps = mSettings.mPackages.get(packageName);
15440            if (ps == null
15441                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15442                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15443            }
15444            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15445        }
15446    }
15447
15448    @Override
15449    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15450        mContext.enforceCallingOrSelfPermission(
15451                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15452
15453        boolean result = false;
15454        synchronized (mPackages) {
15455            final PackageSetting ps = mSettings.mPackages.get(packageName);
15456            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15457                return false;
15458            }
15459            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15460        }
15461        if (result) {
15462            scheduleWritePackageRestrictionsLocked(userId);
15463        }
15464        return result;
15465    }
15466
15467    @Override
15468    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15469            String packageName) {
15470        final int callingUid = Binder.getCallingUid();
15471        if (getInstantAppPackageName(callingUid) != null) {
15472            return ParceledListSlice.emptyList();
15473        }
15474        synchronized (mPackages) {
15475            final PackageSetting ps = mSettings.mPackages.get(packageName);
15476            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15477                return ParceledListSlice.emptyList();
15478            }
15479            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15480        }
15481    }
15482
15483    @Override
15484    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15485        if (TextUtils.isEmpty(packageName)) {
15486            return ParceledListSlice.emptyList();
15487        }
15488        final int callingUid = Binder.getCallingUid();
15489        final int callingUserId = UserHandle.getUserId(callingUid);
15490        synchronized (mPackages) {
15491            PackageParser.Package pkg = mPackages.get(packageName);
15492            if (pkg == null || pkg.activities == null) {
15493                return ParceledListSlice.emptyList();
15494            }
15495            if (pkg.mExtras == null) {
15496                return ParceledListSlice.emptyList();
15497            }
15498            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15499            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15500                return ParceledListSlice.emptyList();
15501            }
15502            final int count = pkg.activities.size();
15503            ArrayList<IntentFilter> result = new ArrayList<>();
15504            for (int n=0; n<count; n++) {
15505                PackageParser.Activity activity = pkg.activities.get(n);
15506                if (activity.intents != null && activity.intents.size() > 0) {
15507                    result.addAll(activity.intents);
15508                }
15509            }
15510            return new ParceledListSlice<>(result);
15511        }
15512    }
15513
15514    @Override
15515    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15516        mContext.enforceCallingOrSelfPermission(
15517                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15518        if (UserHandle.getCallingUserId() != userId) {
15519            mContext.enforceCallingOrSelfPermission(
15520                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15521        }
15522
15523        synchronized (mPackages) {
15524            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15525            if (packageName != null) {
15526                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15527                        packageName, userId);
15528            }
15529            return result;
15530        }
15531    }
15532
15533    @Override
15534    public String getDefaultBrowserPackageName(int userId) {
15535        if (UserHandle.getCallingUserId() != userId) {
15536            mContext.enforceCallingOrSelfPermission(
15537                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15538        }
15539        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15540            return null;
15541        }
15542        synchronized (mPackages) {
15543            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15544        }
15545    }
15546
15547    /**
15548     * Get the "allow unknown sources" setting.
15549     *
15550     * @return the current "allow unknown sources" setting
15551     */
15552    private int getUnknownSourcesSettings() {
15553        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15554                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15555                -1);
15556    }
15557
15558    @Override
15559    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15560        final int callingUid = Binder.getCallingUid();
15561        if (getInstantAppPackageName(callingUid) != null) {
15562            return;
15563        }
15564        // writer
15565        synchronized (mPackages) {
15566            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15567            if (targetPackageSetting == null
15568                    || filterAppAccessLPr(
15569                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15570                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15571            }
15572
15573            PackageSetting installerPackageSetting;
15574            if (installerPackageName != null) {
15575                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15576                if (installerPackageSetting == null) {
15577                    throw new IllegalArgumentException("Unknown installer package: "
15578                            + installerPackageName);
15579                }
15580            } else {
15581                installerPackageSetting = null;
15582            }
15583
15584            Signature[] callerSignature;
15585            Object obj = mSettings.getUserIdLPr(callingUid);
15586            if (obj != null) {
15587                if (obj instanceof SharedUserSetting) {
15588                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15589                } else if (obj instanceof PackageSetting) {
15590                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15591                } else {
15592                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15593                }
15594            } else {
15595                throw new SecurityException("Unknown calling UID: " + callingUid);
15596            }
15597
15598            // Verify: can't set installerPackageName to a package that is
15599            // not signed with the same cert as the caller.
15600            if (installerPackageSetting != null) {
15601                if (compareSignatures(callerSignature,
15602                        installerPackageSetting.signatures.mSignatures)
15603                        != PackageManager.SIGNATURE_MATCH) {
15604                    throw new SecurityException(
15605                            "Caller does not have same cert as new installer package "
15606                            + installerPackageName);
15607                }
15608            }
15609
15610            // Verify: if target already has an installer package, it must
15611            // be signed with the same cert as the caller.
15612            if (targetPackageSetting.installerPackageName != null) {
15613                PackageSetting setting = mSettings.mPackages.get(
15614                        targetPackageSetting.installerPackageName);
15615                // If the currently set package isn't valid, then it's always
15616                // okay to change it.
15617                if (setting != null) {
15618                    if (compareSignatures(callerSignature,
15619                            setting.signatures.mSignatures)
15620                            != PackageManager.SIGNATURE_MATCH) {
15621                        throw new SecurityException(
15622                                "Caller does not have same cert as old installer package "
15623                                + targetPackageSetting.installerPackageName);
15624                    }
15625                }
15626            }
15627
15628            // Okay!
15629            targetPackageSetting.installerPackageName = installerPackageName;
15630            if (installerPackageName != null) {
15631                mSettings.mInstallerPackages.add(installerPackageName);
15632            }
15633            scheduleWriteSettingsLocked();
15634        }
15635    }
15636
15637    @Override
15638    public void setApplicationCategoryHint(String packageName, int categoryHint,
15639            String callerPackageName) {
15640        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15641            throw new SecurityException("Instant applications don't have access to this method");
15642        }
15643        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15644                callerPackageName);
15645        synchronized (mPackages) {
15646            PackageSetting ps = mSettings.mPackages.get(packageName);
15647            if (ps == null) {
15648                throw new IllegalArgumentException("Unknown target package " + packageName);
15649            }
15650            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15651                throw new IllegalArgumentException("Unknown target package " + packageName);
15652            }
15653            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15654                throw new IllegalArgumentException("Calling package " + callerPackageName
15655                        + " is not installer for " + packageName);
15656            }
15657
15658            if (ps.categoryHint != categoryHint) {
15659                ps.categoryHint = categoryHint;
15660                scheduleWriteSettingsLocked();
15661            }
15662        }
15663    }
15664
15665    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15666        // Queue up an async operation since the package installation may take a little while.
15667        mHandler.post(new Runnable() {
15668            public void run() {
15669                mHandler.removeCallbacks(this);
15670                 // Result object to be returned
15671                PackageInstalledInfo res = new PackageInstalledInfo();
15672                res.setReturnCode(currentStatus);
15673                res.uid = -1;
15674                res.pkg = null;
15675                res.removedInfo = null;
15676                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15677                    args.doPreInstall(res.returnCode);
15678                    synchronized (mInstallLock) {
15679                        installPackageTracedLI(args, res);
15680                    }
15681                    args.doPostInstall(res.returnCode, res.uid);
15682                }
15683
15684                // A restore should be performed at this point if (a) the install
15685                // succeeded, (b) the operation is not an update, and (c) the new
15686                // package has not opted out of backup participation.
15687                final boolean update = res.removedInfo != null
15688                        && res.removedInfo.removedPackage != null;
15689                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15690                boolean doRestore = !update
15691                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15692
15693                // Set up the post-install work request bookkeeping.  This will be used
15694                // and cleaned up by the post-install event handling regardless of whether
15695                // there's a restore pass performed.  Token values are >= 1.
15696                int token;
15697                if (mNextInstallToken < 0) mNextInstallToken = 1;
15698                token = mNextInstallToken++;
15699
15700                PostInstallData data = new PostInstallData(args, res);
15701                mRunningInstalls.put(token, data);
15702                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15703
15704                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15705                    // Pass responsibility to the Backup Manager.  It will perform a
15706                    // restore if appropriate, then pass responsibility back to the
15707                    // Package Manager to run the post-install observer callbacks
15708                    // and broadcasts.
15709                    IBackupManager bm = IBackupManager.Stub.asInterface(
15710                            ServiceManager.getService(Context.BACKUP_SERVICE));
15711                    if (bm != null) {
15712                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15713                                + " to BM for possible restore");
15714                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15715                        try {
15716                            // TODO: http://b/22388012
15717                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15718                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15719                            } else {
15720                                doRestore = false;
15721                            }
15722                        } catch (RemoteException e) {
15723                            // can't happen; the backup manager is local
15724                        } catch (Exception e) {
15725                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15726                            doRestore = false;
15727                        }
15728                    } else {
15729                        Slog.e(TAG, "Backup Manager not found!");
15730                        doRestore = false;
15731                    }
15732                }
15733
15734                if (!doRestore) {
15735                    // No restore possible, or the Backup Manager was mysteriously not
15736                    // available -- just fire the post-install work request directly.
15737                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15738
15739                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15740
15741                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15742                    mHandler.sendMessage(msg);
15743                }
15744            }
15745        });
15746    }
15747
15748    /**
15749     * Callback from PackageSettings whenever an app is first transitioned out of the
15750     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15751     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15752     * here whether the app is the target of an ongoing install, and only send the
15753     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15754     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15755     * handling.
15756     */
15757    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15758        // Serialize this with the rest of the install-process message chain.  In the
15759        // restore-at-install case, this Runnable will necessarily run before the
15760        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15761        // are coherent.  In the non-restore case, the app has already completed install
15762        // and been launched through some other means, so it is not in a problematic
15763        // state for observers to see the FIRST_LAUNCH signal.
15764        mHandler.post(new Runnable() {
15765            @Override
15766            public void run() {
15767                for (int i = 0; i < mRunningInstalls.size(); i++) {
15768                    final PostInstallData data = mRunningInstalls.valueAt(i);
15769                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15770                        continue;
15771                    }
15772                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15773                        // right package; but is it for the right user?
15774                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15775                            if (userId == data.res.newUsers[uIndex]) {
15776                                if (DEBUG_BACKUP) {
15777                                    Slog.i(TAG, "Package " + pkgName
15778                                            + " being restored so deferring FIRST_LAUNCH");
15779                                }
15780                                return;
15781                            }
15782                        }
15783                    }
15784                }
15785                // didn't find it, so not being restored
15786                if (DEBUG_BACKUP) {
15787                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15788                }
15789                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15790            }
15791        });
15792    }
15793
15794    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15795        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15796                installerPkg, null, userIds);
15797    }
15798
15799    private abstract class HandlerParams {
15800        private static final int MAX_RETRIES = 4;
15801
15802        /**
15803         * Number of times startCopy() has been attempted and had a non-fatal
15804         * error.
15805         */
15806        private int mRetries = 0;
15807
15808        /** User handle for the user requesting the information or installation. */
15809        private final UserHandle mUser;
15810        String traceMethod;
15811        int traceCookie;
15812
15813        HandlerParams(UserHandle user) {
15814            mUser = user;
15815        }
15816
15817        UserHandle getUser() {
15818            return mUser;
15819        }
15820
15821        HandlerParams setTraceMethod(String traceMethod) {
15822            this.traceMethod = traceMethod;
15823            return this;
15824        }
15825
15826        HandlerParams setTraceCookie(int traceCookie) {
15827            this.traceCookie = traceCookie;
15828            return this;
15829        }
15830
15831        final boolean startCopy() {
15832            boolean res;
15833            try {
15834                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15835
15836                if (++mRetries > MAX_RETRIES) {
15837                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15838                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15839                    handleServiceError();
15840                    return false;
15841                } else {
15842                    handleStartCopy();
15843                    res = true;
15844                }
15845            } catch (RemoteException e) {
15846                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15847                mHandler.sendEmptyMessage(MCS_RECONNECT);
15848                res = false;
15849            }
15850            handleReturnCode();
15851            return res;
15852        }
15853
15854        final void serviceError() {
15855            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15856            handleServiceError();
15857            handleReturnCode();
15858        }
15859
15860        abstract void handleStartCopy() throws RemoteException;
15861        abstract void handleServiceError();
15862        abstract void handleReturnCode();
15863    }
15864
15865    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15866        for (File path : paths) {
15867            try {
15868                mcs.clearDirectory(path.getAbsolutePath());
15869            } catch (RemoteException e) {
15870            }
15871        }
15872    }
15873
15874    static class OriginInfo {
15875        /**
15876         * Location where install is coming from, before it has been
15877         * copied/renamed into place. This could be a single monolithic APK
15878         * file, or a cluster directory. This location may be untrusted.
15879         */
15880        final File file;
15881        final String cid;
15882
15883        /**
15884         * Flag indicating that {@link #file} or {@link #cid} has already been
15885         * staged, meaning downstream users don't need to defensively copy the
15886         * contents.
15887         */
15888        final boolean staged;
15889
15890        /**
15891         * Flag indicating that {@link #file} or {@link #cid} is an already
15892         * installed app that is being moved.
15893         */
15894        final boolean existing;
15895
15896        final String resolvedPath;
15897        final File resolvedFile;
15898
15899        static OriginInfo fromNothing() {
15900            return new OriginInfo(null, null, false, false);
15901        }
15902
15903        static OriginInfo fromUntrustedFile(File file) {
15904            return new OriginInfo(file, null, false, false);
15905        }
15906
15907        static OriginInfo fromExistingFile(File file) {
15908            return new OriginInfo(file, null, false, true);
15909        }
15910
15911        static OriginInfo fromStagedFile(File file) {
15912            return new OriginInfo(file, null, true, false);
15913        }
15914
15915        static OriginInfo fromStagedContainer(String cid) {
15916            return new OriginInfo(null, cid, true, false);
15917        }
15918
15919        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15920            this.file = file;
15921            this.cid = cid;
15922            this.staged = staged;
15923            this.existing = existing;
15924
15925            if (cid != null) {
15926                resolvedPath = PackageHelper.getSdDir(cid);
15927                resolvedFile = new File(resolvedPath);
15928            } else if (file != null) {
15929                resolvedPath = file.getAbsolutePath();
15930                resolvedFile = file;
15931            } else {
15932                resolvedPath = null;
15933                resolvedFile = null;
15934            }
15935        }
15936    }
15937
15938    static class MoveInfo {
15939        final int moveId;
15940        final String fromUuid;
15941        final String toUuid;
15942        final String packageName;
15943        final String dataAppName;
15944        final int appId;
15945        final String seinfo;
15946        final int targetSdkVersion;
15947
15948        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15949                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15950            this.moveId = moveId;
15951            this.fromUuid = fromUuid;
15952            this.toUuid = toUuid;
15953            this.packageName = packageName;
15954            this.dataAppName = dataAppName;
15955            this.appId = appId;
15956            this.seinfo = seinfo;
15957            this.targetSdkVersion = targetSdkVersion;
15958        }
15959    }
15960
15961    static class VerificationInfo {
15962        /** A constant used to indicate that a uid value is not present. */
15963        public static final int NO_UID = -1;
15964
15965        /** URI referencing where the package was downloaded from. */
15966        final Uri originatingUri;
15967
15968        /** HTTP referrer URI associated with the originatingURI. */
15969        final Uri referrer;
15970
15971        /** UID of the application that the install request originated from. */
15972        final int originatingUid;
15973
15974        /** UID of application requesting the install */
15975        final int installerUid;
15976
15977        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15978            this.originatingUri = originatingUri;
15979            this.referrer = referrer;
15980            this.originatingUid = originatingUid;
15981            this.installerUid = installerUid;
15982        }
15983    }
15984
15985    class InstallParams extends HandlerParams {
15986        final OriginInfo origin;
15987        final MoveInfo move;
15988        final IPackageInstallObserver2 observer;
15989        int installFlags;
15990        final String installerPackageName;
15991        final String volumeUuid;
15992        private InstallArgs mArgs;
15993        private int mRet;
15994        final String packageAbiOverride;
15995        final String[] grantedRuntimePermissions;
15996        final VerificationInfo verificationInfo;
15997        final Certificate[][] certificates;
15998        final int installReason;
15999
16000        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16001                int installFlags, String installerPackageName, String volumeUuid,
16002                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
16003                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
16004            super(user);
16005            this.origin = origin;
16006            this.move = move;
16007            this.observer = observer;
16008            this.installFlags = installFlags;
16009            this.installerPackageName = installerPackageName;
16010            this.volumeUuid = volumeUuid;
16011            this.verificationInfo = verificationInfo;
16012            this.packageAbiOverride = packageAbiOverride;
16013            this.grantedRuntimePermissions = grantedPermissions;
16014            this.certificates = certificates;
16015            this.installReason = installReason;
16016        }
16017
16018        @Override
16019        public String toString() {
16020            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
16021                    + " file=" + origin.file + " cid=" + origin.cid + "}";
16022        }
16023
16024        private int installLocationPolicy(PackageInfoLite pkgLite) {
16025            String packageName = pkgLite.packageName;
16026            int installLocation = pkgLite.installLocation;
16027            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16028            // reader
16029            synchronized (mPackages) {
16030                // Currently installed package which the new package is attempting to replace or
16031                // null if no such package is installed.
16032                PackageParser.Package installedPkg = mPackages.get(packageName);
16033                // Package which currently owns the data which the new package will own if installed.
16034                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
16035                // will be null whereas dataOwnerPkg will contain information about the package
16036                // which was uninstalled while keeping its data.
16037                PackageParser.Package dataOwnerPkg = installedPkg;
16038                if (dataOwnerPkg  == null) {
16039                    PackageSetting ps = mSettings.mPackages.get(packageName);
16040                    if (ps != null) {
16041                        dataOwnerPkg = ps.pkg;
16042                    }
16043                }
16044
16045                if (dataOwnerPkg != null) {
16046                    // If installed, the package will get access to data left on the device by its
16047                    // predecessor. As a security measure, this is permited only if this is not a
16048                    // version downgrade or if the predecessor package is marked as debuggable and
16049                    // a downgrade is explicitly requested.
16050                    //
16051                    // On debuggable platform builds, downgrades are permitted even for
16052                    // non-debuggable packages to make testing easier. Debuggable platform builds do
16053                    // not offer security guarantees and thus it's OK to disable some security
16054                    // mechanisms to make debugging/testing easier on those builds. However, even on
16055                    // debuggable builds downgrades of packages are permitted only if requested via
16056                    // installFlags. This is because we aim to keep the behavior of debuggable
16057                    // platform builds as close as possible to the behavior of non-debuggable
16058                    // platform builds.
16059                    final boolean downgradeRequested =
16060                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
16061                    final boolean packageDebuggable =
16062                                (dataOwnerPkg.applicationInfo.flags
16063                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
16064                    final boolean downgradePermitted =
16065                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
16066                    if (!downgradePermitted) {
16067                        try {
16068                            checkDowngrade(dataOwnerPkg, pkgLite);
16069                        } catch (PackageManagerException e) {
16070                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
16071                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
16072                        }
16073                    }
16074                }
16075
16076                if (installedPkg != null) {
16077                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16078                        // Check for updated system application.
16079                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16080                            if (onSd) {
16081                                Slog.w(TAG, "Cannot install update to system app on sdcard");
16082                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
16083                            }
16084                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16085                        } else {
16086                            if (onSd) {
16087                                // Install flag overrides everything.
16088                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16089                            }
16090                            // If current upgrade specifies particular preference
16091                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
16092                                // Application explicitly specified internal.
16093                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16094                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
16095                                // App explictly prefers external. Let policy decide
16096                            } else {
16097                                // Prefer previous location
16098                                if (isExternal(installedPkg)) {
16099                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16100                                }
16101                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16102                            }
16103                        }
16104                    } else {
16105                        // Invalid install. Return error code
16106                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
16107                    }
16108                }
16109            }
16110            // All the special cases have been taken care of.
16111            // Return result based on recommended install location.
16112            if (onSd) {
16113                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16114            }
16115            return pkgLite.recommendedInstallLocation;
16116        }
16117
16118        /*
16119         * Invoke remote method to get package information and install
16120         * location values. Override install location based on default
16121         * policy if needed and then create install arguments based
16122         * on the install location.
16123         */
16124        public void handleStartCopy() throws RemoteException {
16125            int ret = PackageManager.INSTALL_SUCCEEDED;
16126
16127            // If we're already staged, we've firmly committed to an install location
16128            if (origin.staged) {
16129                if (origin.file != null) {
16130                    installFlags |= PackageManager.INSTALL_INTERNAL;
16131                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16132                } else if (origin.cid != null) {
16133                    installFlags |= PackageManager.INSTALL_EXTERNAL;
16134                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
16135                } else {
16136                    throw new IllegalStateException("Invalid stage location");
16137                }
16138            }
16139
16140            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16141            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
16142            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16143            PackageInfoLite pkgLite = null;
16144
16145            if (onInt && onSd) {
16146                // Check if both bits are set.
16147                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
16148                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16149            } else if (onSd && ephemeral) {
16150                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
16151                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16152            } else {
16153                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
16154                        packageAbiOverride);
16155
16156                if (DEBUG_EPHEMERAL && ephemeral) {
16157                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
16158                }
16159
16160                /*
16161                 * If we have too little free space, try to free cache
16162                 * before giving up.
16163                 */
16164                if (!origin.staged && pkgLite.recommendedInstallLocation
16165                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16166                    // TODO: focus freeing disk space on the target device
16167                    final StorageManager storage = StorageManager.from(mContext);
16168                    final long lowThreshold = storage.getStorageLowBytes(
16169                            Environment.getDataDirectory());
16170
16171                    final long sizeBytes = mContainerService.calculateInstalledSize(
16172                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
16173
16174                    try {
16175                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
16176                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
16177                                installFlags, packageAbiOverride);
16178                    } catch (InstallerException e) {
16179                        Slog.w(TAG, "Failed to free cache", e);
16180                    }
16181
16182                    /*
16183                     * The cache free must have deleted the file we
16184                     * downloaded to install.
16185                     *
16186                     * TODO: fix the "freeCache" call to not delete
16187                     *       the file we care about.
16188                     */
16189                    if (pkgLite.recommendedInstallLocation
16190                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16191                        pkgLite.recommendedInstallLocation
16192                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
16193                    }
16194                }
16195            }
16196
16197            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16198                int loc = pkgLite.recommendedInstallLocation;
16199                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
16200                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16201                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
16202                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
16203                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16204                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16205                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
16206                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
16207                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16208                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
16209                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
16210                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
16211                } else {
16212                    // Override with defaults if needed.
16213                    loc = installLocationPolicy(pkgLite);
16214                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
16215                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
16216                    } else if (!onSd && !onInt) {
16217                        // Override install location with flags
16218                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
16219                            // Set the flag to install on external media.
16220                            installFlags |= PackageManager.INSTALL_EXTERNAL;
16221                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
16222                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
16223                            if (DEBUG_EPHEMERAL) {
16224                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
16225                            }
16226                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
16227                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
16228                                    |PackageManager.INSTALL_INTERNAL);
16229                        } else {
16230                            // Make sure the flag for installing on external
16231                            // media is unset
16232                            installFlags |= PackageManager.INSTALL_INTERNAL;
16233                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16234                        }
16235                    }
16236                }
16237            }
16238
16239            final InstallArgs args = createInstallArgs(this);
16240            mArgs = args;
16241
16242            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16243                // TODO: http://b/22976637
16244                // Apps installed for "all" users use the device owner to verify the app
16245                UserHandle verifierUser = getUser();
16246                if (verifierUser == UserHandle.ALL) {
16247                    verifierUser = UserHandle.SYSTEM;
16248                }
16249
16250                /*
16251                 * Determine if we have any installed package verifiers. If we
16252                 * do, then we'll defer to them to verify the packages.
16253                 */
16254                final int requiredUid = mRequiredVerifierPackage == null ? -1
16255                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16256                                verifierUser.getIdentifier());
16257                final int installerUid =
16258                        verificationInfo == null ? -1 : verificationInfo.installerUid;
16259                if (!origin.existing && requiredUid != -1
16260                        && isVerificationEnabled(
16261                                verifierUser.getIdentifier(), installFlags, installerUid)) {
16262                    final Intent verification = new Intent(
16263                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
16264                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
16265                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
16266                            PACKAGE_MIME_TYPE);
16267                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
16268
16269                    // Query all live verifiers based on current user state
16270                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
16271                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
16272                            false /*allowDynamicSplits*/);
16273
16274                    if (DEBUG_VERIFY) {
16275                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
16276                                + verification.toString() + " with " + pkgLite.verifiers.length
16277                                + " optional verifiers");
16278                    }
16279
16280                    final int verificationId = mPendingVerificationToken++;
16281
16282                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
16283
16284                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
16285                            installerPackageName);
16286
16287                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
16288                            installFlags);
16289
16290                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
16291                            pkgLite.packageName);
16292
16293                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
16294                            pkgLite.versionCode);
16295
16296                    if (verificationInfo != null) {
16297                        if (verificationInfo.originatingUri != null) {
16298                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
16299                                    verificationInfo.originatingUri);
16300                        }
16301                        if (verificationInfo.referrer != null) {
16302                            verification.putExtra(Intent.EXTRA_REFERRER,
16303                                    verificationInfo.referrer);
16304                        }
16305                        if (verificationInfo.originatingUid >= 0) {
16306                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
16307                                    verificationInfo.originatingUid);
16308                        }
16309                        if (verificationInfo.installerUid >= 0) {
16310                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
16311                                    verificationInfo.installerUid);
16312                        }
16313                    }
16314
16315                    final PackageVerificationState verificationState = new PackageVerificationState(
16316                            requiredUid, args);
16317
16318                    mPendingVerification.append(verificationId, verificationState);
16319
16320                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
16321                            receivers, verificationState);
16322
16323                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
16324                    final long idleDuration = getVerificationTimeout();
16325
16326                    /*
16327                     * If any sufficient verifiers were listed in the package
16328                     * manifest, attempt to ask them.
16329                     */
16330                    if (sufficientVerifiers != null) {
16331                        final int N = sufficientVerifiers.size();
16332                        if (N == 0) {
16333                            Slog.i(TAG, "Additional verifiers required, but none installed.");
16334                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
16335                        } else {
16336                            for (int i = 0; i < N; i++) {
16337                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
16338                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16339                                        verifierComponent.getPackageName(), idleDuration,
16340                                        verifierUser.getIdentifier(), false, "package verifier");
16341
16342                                final Intent sufficientIntent = new Intent(verification);
16343                                sufficientIntent.setComponent(verifierComponent);
16344                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
16345                            }
16346                        }
16347                    }
16348
16349                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
16350                            mRequiredVerifierPackage, receivers);
16351                    if (ret == PackageManager.INSTALL_SUCCEEDED
16352                            && mRequiredVerifierPackage != null) {
16353                        Trace.asyncTraceBegin(
16354                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
16355                        /*
16356                         * Send the intent to the required verification agent,
16357                         * but only start the verification timeout after the
16358                         * target BroadcastReceivers have run.
16359                         */
16360                        verification.setComponent(requiredVerifierComponent);
16361                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16362                                mRequiredVerifierPackage, idleDuration,
16363                                verifierUser.getIdentifier(), false, "package verifier");
16364                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16365                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16366                                new BroadcastReceiver() {
16367                                    @Override
16368                                    public void onReceive(Context context, Intent intent) {
16369                                        final Message msg = mHandler
16370                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
16371                                        msg.arg1 = verificationId;
16372                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16373                                    }
16374                                }, null, 0, null, null);
16375
16376                        /*
16377                         * We don't want the copy to proceed until verification
16378                         * succeeds, so null out this field.
16379                         */
16380                        mArgs = null;
16381                    }
16382                } else {
16383                    /*
16384                     * No package verification is enabled, so immediately start
16385                     * the remote call to initiate copy using temporary file.
16386                     */
16387                    ret = args.copyApk(mContainerService, true);
16388                }
16389            }
16390
16391            mRet = ret;
16392        }
16393
16394        @Override
16395        void handleReturnCode() {
16396            // If mArgs is null, then MCS couldn't be reached. When it
16397            // reconnects, it will try again to install. At that point, this
16398            // will succeed.
16399            if (mArgs != null) {
16400                processPendingInstall(mArgs, mRet);
16401            }
16402        }
16403
16404        @Override
16405        void handleServiceError() {
16406            mArgs = createInstallArgs(this);
16407            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16408        }
16409
16410        public boolean isForwardLocked() {
16411            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16412        }
16413    }
16414
16415    /**
16416     * Used during creation of InstallArgs
16417     *
16418     * @param installFlags package installation flags
16419     * @return true if should be installed on external storage
16420     */
16421    private static boolean installOnExternalAsec(int installFlags) {
16422        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16423            return false;
16424        }
16425        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16426            return true;
16427        }
16428        return false;
16429    }
16430
16431    /**
16432     * Used during creation of InstallArgs
16433     *
16434     * @param installFlags package installation flags
16435     * @return true if should be installed as forward locked
16436     */
16437    private static boolean installForwardLocked(int installFlags) {
16438        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16439    }
16440
16441    private InstallArgs createInstallArgs(InstallParams params) {
16442        if (params.move != null) {
16443            return new MoveInstallArgs(params);
16444        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16445            return new AsecInstallArgs(params);
16446        } else {
16447            return new FileInstallArgs(params);
16448        }
16449    }
16450
16451    /**
16452     * Create args that describe an existing installed package. Typically used
16453     * when cleaning up old installs, or used as a move source.
16454     */
16455    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16456            String resourcePath, String[] instructionSets) {
16457        final boolean isInAsec;
16458        if (installOnExternalAsec(installFlags)) {
16459            /* Apps on SD card are always in ASEC containers. */
16460            isInAsec = true;
16461        } else if (installForwardLocked(installFlags)
16462                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16463            /*
16464             * Forward-locked apps are only in ASEC containers if they're the
16465             * new style
16466             */
16467            isInAsec = true;
16468        } else {
16469            isInAsec = false;
16470        }
16471
16472        if (isInAsec) {
16473            return new AsecInstallArgs(codePath, instructionSets,
16474                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16475        } else {
16476            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16477        }
16478    }
16479
16480    static abstract class InstallArgs {
16481        /** @see InstallParams#origin */
16482        final OriginInfo origin;
16483        /** @see InstallParams#move */
16484        final MoveInfo move;
16485
16486        final IPackageInstallObserver2 observer;
16487        // Always refers to PackageManager flags only
16488        final int installFlags;
16489        final String installerPackageName;
16490        final String volumeUuid;
16491        final UserHandle user;
16492        final String abiOverride;
16493        final String[] installGrantPermissions;
16494        /** If non-null, drop an async trace when the install completes */
16495        final String traceMethod;
16496        final int traceCookie;
16497        final Certificate[][] certificates;
16498        final int installReason;
16499
16500        // The list of instruction sets supported by this app. This is currently
16501        // only used during the rmdex() phase to clean up resources. We can get rid of this
16502        // if we move dex files under the common app path.
16503        /* nullable */ String[] instructionSets;
16504
16505        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16506                int installFlags, String installerPackageName, String volumeUuid,
16507                UserHandle user, String[] instructionSets,
16508                String abiOverride, String[] installGrantPermissions,
16509                String traceMethod, int traceCookie, Certificate[][] certificates,
16510                int installReason) {
16511            this.origin = origin;
16512            this.move = move;
16513            this.installFlags = installFlags;
16514            this.observer = observer;
16515            this.installerPackageName = installerPackageName;
16516            this.volumeUuid = volumeUuid;
16517            this.user = user;
16518            this.instructionSets = instructionSets;
16519            this.abiOverride = abiOverride;
16520            this.installGrantPermissions = installGrantPermissions;
16521            this.traceMethod = traceMethod;
16522            this.traceCookie = traceCookie;
16523            this.certificates = certificates;
16524            this.installReason = installReason;
16525        }
16526
16527        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16528        abstract int doPreInstall(int status);
16529
16530        /**
16531         * Rename package into final resting place. All paths on the given
16532         * scanned package should be updated to reflect the rename.
16533         */
16534        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16535        abstract int doPostInstall(int status, int uid);
16536
16537        /** @see PackageSettingBase#codePathString */
16538        abstract String getCodePath();
16539        /** @see PackageSettingBase#resourcePathString */
16540        abstract String getResourcePath();
16541
16542        // Need installer lock especially for dex file removal.
16543        abstract void cleanUpResourcesLI();
16544        abstract boolean doPostDeleteLI(boolean delete);
16545
16546        /**
16547         * Called before the source arguments are copied. This is used mostly
16548         * for MoveParams when it needs to read the source file to put it in the
16549         * destination.
16550         */
16551        int doPreCopy() {
16552            return PackageManager.INSTALL_SUCCEEDED;
16553        }
16554
16555        /**
16556         * Called after the source arguments are copied. This is used mostly for
16557         * MoveParams when it needs to read the source file to put it in the
16558         * destination.
16559         */
16560        int doPostCopy(int uid) {
16561            return PackageManager.INSTALL_SUCCEEDED;
16562        }
16563
16564        protected boolean isFwdLocked() {
16565            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16566        }
16567
16568        protected boolean isExternalAsec() {
16569            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16570        }
16571
16572        protected boolean isEphemeral() {
16573            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16574        }
16575
16576        UserHandle getUser() {
16577            return user;
16578        }
16579    }
16580
16581    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16582        if (!allCodePaths.isEmpty()) {
16583            if (instructionSets == null) {
16584                throw new IllegalStateException("instructionSet == null");
16585            }
16586            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16587            for (String codePath : allCodePaths) {
16588                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16589                    try {
16590                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16591                    } catch (InstallerException ignored) {
16592                    }
16593                }
16594            }
16595        }
16596    }
16597
16598    /**
16599     * Logic to handle installation of non-ASEC applications, including copying
16600     * and renaming logic.
16601     */
16602    class FileInstallArgs extends InstallArgs {
16603        private File codeFile;
16604        private File resourceFile;
16605
16606        // Example topology:
16607        // /data/app/com.example/base.apk
16608        // /data/app/com.example/split_foo.apk
16609        // /data/app/com.example/lib/arm/libfoo.so
16610        // /data/app/com.example/lib/arm64/libfoo.so
16611        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16612
16613        /** New install */
16614        FileInstallArgs(InstallParams params) {
16615            super(params.origin, params.move, params.observer, params.installFlags,
16616                    params.installerPackageName, params.volumeUuid,
16617                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16618                    params.grantedRuntimePermissions,
16619                    params.traceMethod, params.traceCookie, params.certificates,
16620                    params.installReason);
16621            if (isFwdLocked()) {
16622                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16623            }
16624        }
16625
16626        /** Existing install */
16627        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16628            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16629                    null, null, null, 0, null /*certificates*/,
16630                    PackageManager.INSTALL_REASON_UNKNOWN);
16631            this.codeFile = (codePath != null) ? new File(codePath) : null;
16632            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16633        }
16634
16635        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16636            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16637            try {
16638                return doCopyApk(imcs, temp);
16639            } finally {
16640                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16641            }
16642        }
16643
16644        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16645            if (origin.staged) {
16646                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16647                codeFile = origin.file;
16648                resourceFile = origin.file;
16649                return PackageManager.INSTALL_SUCCEEDED;
16650            }
16651
16652            try {
16653                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16654                final File tempDir =
16655                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16656                codeFile = tempDir;
16657                resourceFile = tempDir;
16658            } catch (IOException e) {
16659                Slog.w(TAG, "Failed to create copy file: " + e);
16660                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16661            }
16662
16663            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16664                @Override
16665                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16666                    if (!FileUtils.isValidExtFilename(name)) {
16667                        throw new IllegalArgumentException("Invalid filename: " + name);
16668                    }
16669                    try {
16670                        final File file = new File(codeFile, name);
16671                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16672                                O_RDWR | O_CREAT, 0644);
16673                        Os.chmod(file.getAbsolutePath(), 0644);
16674                        return new ParcelFileDescriptor(fd);
16675                    } catch (ErrnoException e) {
16676                        throw new RemoteException("Failed to open: " + e.getMessage());
16677                    }
16678                }
16679            };
16680
16681            int ret = PackageManager.INSTALL_SUCCEEDED;
16682            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16683            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16684                Slog.e(TAG, "Failed to copy package");
16685                return ret;
16686            }
16687
16688            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16689            NativeLibraryHelper.Handle handle = null;
16690            try {
16691                handle = NativeLibraryHelper.Handle.create(codeFile);
16692                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16693                        abiOverride);
16694            } catch (IOException e) {
16695                Slog.e(TAG, "Copying native libraries failed", e);
16696                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16697            } finally {
16698                IoUtils.closeQuietly(handle);
16699            }
16700
16701            return ret;
16702        }
16703
16704        int doPreInstall(int status) {
16705            if (status != PackageManager.INSTALL_SUCCEEDED) {
16706                cleanUp();
16707            }
16708            return status;
16709        }
16710
16711        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16712            if (status != PackageManager.INSTALL_SUCCEEDED) {
16713                cleanUp();
16714                return false;
16715            }
16716
16717            final File targetDir = codeFile.getParentFile();
16718            final File beforeCodeFile = codeFile;
16719            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16720
16721            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16722            try {
16723                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16724            } catch (ErrnoException e) {
16725                Slog.w(TAG, "Failed to rename", e);
16726                return false;
16727            }
16728
16729            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16730                Slog.w(TAG, "Failed to restorecon");
16731                return false;
16732            }
16733
16734            // Reflect the rename internally
16735            codeFile = afterCodeFile;
16736            resourceFile = afterCodeFile;
16737
16738            // Reflect the rename in scanned details
16739            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16740            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16741                    afterCodeFile, pkg.baseCodePath));
16742            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16743                    afterCodeFile, pkg.splitCodePaths));
16744
16745            // Reflect the rename in app info
16746            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16747            pkg.setApplicationInfoCodePath(pkg.codePath);
16748            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16749            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16750            pkg.setApplicationInfoResourcePath(pkg.codePath);
16751            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16752            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16753
16754            return true;
16755        }
16756
16757        int doPostInstall(int status, int uid) {
16758            if (status != PackageManager.INSTALL_SUCCEEDED) {
16759                cleanUp();
16760            }
16761            return status;
16762        }
16763
16764        @Override
16765        String getCodePath() {
16766            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16767        }
16768
16769        @Override
16770        String getResourcePath() {
16771            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16772        }
16773
16774        private boolean cleanUp() {
16775            if (codeFile == null || !codeFile.exists()) {
16776                return false;
16777            }
16778
16779            removeCodePathLI(codeFile);
16780
16781            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16782                resourceFile.delete();
16783            }
16784
16785            return true;
16786        }
16787
16788        void cleanUpResourcesLI() {
16789            // Try enumerating all code paths before deleting
16790            List<String> allCodePaths = Collections.EMPTY_LIST;
16791            if (codeFile != null && codeFile.exists()) {
16792                try {
16793                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16794                    allCodePaths = pkg.getAllCodePaths();
16795                } catch (PackageParserException e) {
16796                    // Ignored; we tried our best
16797                }
16798            }
16799
16800            cleanUp();
16801            removeDexFiles(allCodePaths, instructionSets);
16802        }
16803
16804        boolean doPostDeleteLI(boolean delete) {
16805            // XXX err, shouldn't we respect the delete flag?
16806            cleanUpResourcesLI();
16807            return true;
16808        }
16809    }
16810
16811    private boolean isAsecExternal(String cid) {
16812        final String asecPath = PackageHelper.getSdFilesystem(cid);
16813        return !asecPath.startsWith(mAsecInternalPath);
16814    }
16815
16816    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16817            PackageManagerException {
16818        if (copyRet < 0) {
16819            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16820                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16821                throw new PackageManagerException(copyRet, message);
16822            }
16823        }
16824    }
16825
16826    /**
16827     * Extract the StorageManagerService "container ID" from the full code path of an
16828     * .apk.
16829     */
16830    static String cidFromCodePath(String fullCodePath) {
16831        int eidx = fullCodePath.lastIndexOf("/");
16832        String subStr1 = fullCodePath.substring(0, eidx);
16833        int sidx = subStr1.lastIndexOf("/");
16834        return subStr1.substring(sidx+1, eidx);
16835    }
16836
16837    /**
16838     * Logic to handle installation of ASEC applications, including copying and
16839     * renaming logic.
16840     */
16841    class AsecInstallArgs extends InstallArgs {
16842        static final String RES_FILE_NAME = "pkg.apk";
16843        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16844
16845        String cid;
16846        String packagePath;
16847        String resourcePath;
16848
16849        /** New install */
16850        AsecInstallArgs(InstallParams params) {
16851            super(params.origin, params.move, params.observer, params.installFlags,
16852                    params.installerPackageName, params.volumeUuid,
16853                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16854                    params.grantedRuntimePermissions,
16855                    params.traceMethod, params.traceCookie, params.certificates,
16856                    params.installReason);
16857        }
16858
16859        /** Existing install */
16860        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16861                        boolean isExternal, boolean isForwardLocked) {
16862            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16863                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16864                    instructionSets, null, null, null, 0, null /*certificates*/,
16865                    PackageManager.INSTALL_REASON_UNKNOWN);
16866            // Hackily pretend we're still looking at a full code path
16867            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16868                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16869            }
16870
16871            // Extract cid from fullCodePath
16872            int eidx = fullCodePath.lastIndexOf("/");
16873            String subStr1 = fullCodePath.substring(0, eidx);
16874            int sidx = subStr1.lastIndexOf("/");
16875            cid = subStr1.substring(sidx+1, eidx);
16876            setMountPath(subStr1);
16877        }
16878
16879        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16880            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16881                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16882                    instructionSets, null, null, null, 0, null /*certificates*/,
16883                    PackageManager.INSTALL_REASON_UNKNOWN);
16884            this.cid = cid;
16885            setMountPath(PackageHelper.getSdDir(cid));
16886        }
16887
16888        void createCopyFile() {
16889            cid = mInstallerService.allocateExternalStageCidLegacy();
16890        }
16891
16892        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16893            if (origin.staged && origin.cid != null) {
16894                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16895                cid = origin.cid;
16896                setMountPath(PackageHelper.getSdDir(cid));
16897                return PackageManager.INSTALL_SUCCEEDED;
16898            }
16899
16900            if (temp) {
16901                createCopyFile();
16902            } else {
16903                /*
16904                 * Pre-emptively destroy the container since it's destroyed if
16905                 * copying fails due to it existing anyway.
16906                 */
16907                PackageHelper.destroySdDir(cid);
16908            }
16909
16910            final String newMountPath = imcs.copyPackageToContainer(
16911                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16912                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16913
16914            if (newMountPath != null) {
16915                setMountPath(newMountPath);
16916                return PackageManager.INSTALL_SUCCEEDED;
16917            } else {
16918                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16919            }
16920        }
16921
16922        @Override
16923        String getCodePath() {
16924            return packagePath;
16925        }
16926
16927        @Override
16928        String getResourcePath() {
16929            return resourcePath;
16930        }
16931
16932        int doPreInstall(int status) {
16933            if (status != PackageManager.INSTALL_SUCCEEDED) {
16934                // Destroy container
16935                PackageHelper.destroySdDir(cid);
16936            } else {
16937                boolean mounted = PackageHelper.isContainerMounted(cid);
16938                if (!mounted) {
16939                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16940                            Process.SYSTEM_UID);
16941                    if (newMountPath != null) {
16942                        setMountPath(newMountPath);
16943                    } else {
16944                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16945                    }
16946                }
16947            }
16948            return status;
16949        }
16950
16951        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16952            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16953            String newMountPath = null;
16954            if (PackageHelper.isContainerMounted(cid)) {
16955                // Unmount the container
16956                if (!PackageHelper.unMountSdDir(cid)) {
16957                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16958                    return false;
16959                }
16960            }
16961            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16962                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16963                        " which might be stale. Will try to clean up.");
16964                // Clean up the stale container and proceed to recreate.
16965                if (!PackageHelper.destroySdDir(newCacheId)) {
16966                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16967                    return false;
16968                }
16969                // Successfully cleaned up stale container. Try to rename again.
16970                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16971                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16972                            + " inspite of cleaning it up.");
16973                    return false;
16974                }
16975            }
16976            if (!PackageHelper.isContainerMounted(newCacheId)) {
16977                Slog.w(TAG, "Mounting container " + newCacheId);
16978                newMountPath = PackageHelper.mountSdDir(newCacheId,
16979                        getEncryptKey(), Process.SYSTEM_UID);
16980            } else {
16981                newMountPath = PackageHelper.getSdDir(newCacheId);
16982            }
16983            if (newMountPath == null) {
16984                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16985                return false;
16986            }
16987            Log.i(TAG, "Succesfully renamed " + cid +
16988                    " to " + newCacheId +
16989                    " at new path: " + newMountPath);
16990            cid = newCacheId;
16991
16992            final File beforeCodeFile = new File(packagePath);
16993            setMountPath(newMountPath);
16994            final File afterCodeFile = new File(packagePath);
16995
16996            // Reflect the rename in scanned details
16997            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16998            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16999                    afterCodeFile, pkg.baseCodePath));
17000            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
17001                    afterCodeFile, pkg.splitCodePaths));
17002
17003            // Reflect the rename in app info
17004            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17005            pkg.setApplicationInfoCodePath(pkg.codePath);
17006            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17007            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17008            pkg.setApplicationInfoResourcePath(pkg.codePath);
17009            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17010            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17011
17012            return true;
17013        }
17014
17015        private void setMountPath(String mountPath) {
17016            final File mountFile = new File(mountPath);
17017
17018            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
17019            if (monolithicFile.exists()) {
17020                packagePath = monolithicFile.getAbsolutePath();
17021                if (isFwdLocked()) {
17022                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
17023                } else {
17024                    resourcePath = packagePath;
17025                }
17026            } else {
17027                packagePath = mountFile.getAbsolutePath();
17028                resourcePath = packagePath;
17029            }
17030        }
17031
17032        int doPostInstall(int status, int uid) {
17033            if (status != PackageManager.INSTALL_SUCCEEDED) {
17034                cleanUp();
17035            } else {
17036                final int groupOwner;
17037                final String protectedFile;
17038                if (isFwdLocked()) {
17039                    groupOwner = UserHandle.getSharedAppGid(uid);
17040                    protectedFile = RES_FILE_NAME;
17041                } else {
17042                    groupOwner = -1;
17043                    protectedFile = null;
17044                }
17045
17046                if (uid < Process.FIRST_APPLICATION_UID
17047                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
17048                    Slog.e(TAG, "Failed to finalize " + cid);
17049                    PackageHelper.destroySdDir(cid);
17050                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17051                }
17052
17053                boolean mounted = PackageHelper.isContainerMounted(cid);
17054                if (!mounted) {
17055                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
17056                }
17057            }
17058            return status;
17059        }
17060
17061        private void cleanUp() {
17062            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
17063
17064            // Destroy secure container
17065            PackageHelper.destroySdDir(cid);
17066        }
17067
17068        private List<String> getAllCodePaths() {
17069            final File codeFile = new File(getCodePath());
17070            if (codeFile != null && codeFile.exists()) {
17071                try {
17072                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
17073                    return pkg.getAllCodePaths();
17074                } catch (PackageParserException e) {
17075                    // Ignored; we tried our best
17076                }
17077            }
17078            return Collections.EMPTY_LIST;
17079        }
17080
17081        void cleanUpResourcesLI() {
17082            // Enumerate all code paths before deleting
17083            cleanUpResourcesLI(getAllCodePaths());
17084        }
17085
17086        private void cleanUpResourcesLI(List<String> allCodePaths) {
17087            cleanUp();
17088            removeDexFiles(allCodePaths, instructionSets);
17089        }
17090
17091        String getPackageName() {
17092            return getAsecPackageName(cid);
17093        }
17094
17095        boolean doPostDeleteLI(boolean delete) {
17096            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
17097            final List<String> allCodePaths = getAllCodePaths();
17098            boolean mounted = PackageHelper.isContainerMounted(cid);
17099            if (mounted) {
17100                // Unmount first
17101                if (PackageHelper.unMountSdDir(cid)) {
17102                    mounted = false;
17103                }
17104            }
17105            if (!mounted && delete) {
17106                cleanUpResourcesLI(allCodePaths);
17107            }
17108            return !mounted;
17109        }
17110
17111        @Override
17112        int doPreCopy() {
17113            if (isFwdLocked()) {
17114                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
17115                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
17116                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17117                }
17118            }
17119
17120            return PackageManager.INSTALL_SUCCEEDED;
17121        }
17122
17123        @Override
17124        int doPostCopy(int uid) {
17125            if (isFwdLocked()) {
17126                if (uid < Process.FIRST_APPLICATION_UID
17127                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
17128                                RES_FILE_NAME)) {
17129                    Slog.e(TAG, "Failed to finalize " + cid);
17130                    PackageHelper.destroySdDir(cid);
17131                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17132                }
17133            }
17134
17135            return PackageManager.INSTALL_SUCCEEDED;
17136        }
17137    }
17138
17139    /**
17140     * Logic to handle movement of existing installed applications.
17141     */
17142    class MoveInstallArgs extends InstallArgs {
17143        private File codeFile;
17144        private File resourceFile;
17145
17146        /** New install */
17147        MoveInstallArgs(InstallParams params) {
17148            super(params.origin, params.move, params.observer, params.installFlags,
17149                    params.installerPackageName, params.volumeUuid,
17150                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
17151                    params.grantedRuntimePermissions,
17152                    params.traceMethod, params.traceCookie, params.certificates,
17153                    params.installReason);
17154        }
17155
17156        int copyApk(IMediaContainerService imcs, boolean temp) {
17157            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
17158                    + move.fromUuid + " to " + move.toUuid);
17159            synchronized (mInstaller) {
17160                try {
17161                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
17162                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
17163                } catch (InstallerException e) {
17164                    Slog.w(TAG, "Failed to move app", e);
17165                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
17166                }
17167            }
17168
17169            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
17170            resourceFile = codeFile;
17171            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
17172
17173            return PackageManager.INSTALL_SUCCEEDED;
17174        }
17175
17176        int doPreInstall(int status) {
17177            if (status != PackageManager.INSTALL_SUCCEEDED) {
17178                cleanUp(move.toUuid);
17179            }
17180            return status;
17181        }
17182
17183        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17184            if (status != PackageManager.INSTALL_SUCCEEDED) {
17185                cleanUp(move.toUuid);
17186                return false;
17187            }
17188
17189            // Reflect the move in app info
17190            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17191            pkg.setApplicationInfoCodePath(pkg.codePath);
17192            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17193            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17194            pkg.setApplicationInfoResourcePath(pkg.codePath);
17195            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17196            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17197
17198            return true;
17199        }
17200
17201        int doPostInstall(int status, int uid) {
17202            if (status == PackageManager.INSTALL_SUCCEEDED) {
17203                cleanUp(move.fromUuid);
17204            } else {
17205                cleanUp(move.toUuid);
17206            }
17207            return status;
17208        }
17209
17210        @Override
17211        String getCodePath() {
17212            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
17213        }
17214
17215        @Override
17216        String getResourcePath() {
17217            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
17218        }
17219
17220        private boolean cleanUp(String volumeUuid) {
17221            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
17222                    move.dataAppName);
17223            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
17224            final int[] userIds = sUserManager.getUserIds();
17225            synchronized (mInstallLock) {
17226                // Clean up both app data and code
17227                // All package moves are frozen until finished
17228                for (int userId : userIds) {
17229                    try {
17230                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
17231                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
17232                    } catch (InstallerException e) {
17233                        Slog.w(TAG, String.valueOf(e));
17234                    }
17235                }
17236                removeCodePathLI(codeFile);
17237            }
17238            return true;
17239        }
17240
17241        void cleanUpResourcesLI() {
17242            throw new UnsupportedOperationException();
17243        }
17244
17245        boolean doPostDeleteLI(boolean delete) {
17246            throw new UnsupportedOperationException();
17247        }
17248    }
17249
17250    static String getAsecPackageName(String packageCid) {
17251        int idx = packageCid.lastIndexOf("-");
17252        if (idx == -1) {
17253            return packageCid;
17254        }
17255        return packageCid.substring(0, idx);
17256    }
17257
17258    // Utility method used to create code paths based on package name and available index.
17259    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
17260        String idxStr = "";
17261        int idx = 1;
17262        // Fall back to default value of idx=1 if prefix is not
17263        // part of oldCodePath
17264        if (oldCodePath != null) {
17265            String subStr = oldCodePath;
17266            // Drop the suffix right away
17267            if (suffix != null && subStr.endsWith(suffix)) {
17268                subStr = subStr.substring(0, subStr.length() - suffix.length());
17269            }
17270            // If oldCodePath already contains prefix find out the
17271            // ending index to either increment or decrement.
17272            int sidx = subStr.lastIndexOf(prefix);
17273            if (sidx != -1) {
17274                subStr = subStr.substring(sidx + prefix.length());
17275                if (subStr != null) {
17276                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
17277                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
17278                    }
17279                    try {
17280                        idx = Integer.parseInt(subStr);
17281                        if (idx <= 1) {
17282                            idx++;
17283                        } else {
17284                            idx--;
17285                        }
17286                    } catch(NumberFormatException e) {
17287                    }
17288                }
17289            }
17290        }
17291        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
17292        return prefix + idxStr;
17293    }
17294
17295    private File getNextCodePath(File targetDir, String packageName) {
17296        File result;
17297        SecureRandom random = new SecureRandom();
17298        byte[] bytes = new byte[16];
17299        do {
17300            random.nextBytes(bytes);
17301            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
17302            result = new File(targetDir, packageName + "-" + suffix);
17303        } while (result.exists());
17304        return result;
17305    }
17306
17307    // Utility method that returns the relative package path with respect
17308    // to the installation directory. Like say for /data/data/com.test-1.apk
17309    // string com.test-1 is returned.
17310    static String deriveCodePathName(String codePath) {
17311        if (codePath == null) {
17312            return null;
17313        }
17314        final File codeFile = new File(codePath);
17315        final String name = codeFile.getName();
17316        if (codeFile.isDirectory()) {
17317            return name;
17318        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
17319            final int lastDot = name.lastIndexOf('.');
17320            return name.substring(0, lastDot);
17321        } else {
17322            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
17323            return null;
17324        }
17325    }
17326
17327    static class PackageInstalledInfo {
17328        String name;
17329        int uid;
17330        // The set of users that originally had this package installed.
17331        int[] origUsers;
17332        // The set of users that now have this package installed.
17333        int[] newUsers;
17334        PackageParser.Package pkg;
17335        int returnCode;
17336        String returnMsg;
17337        String installerPackageName;
17338        PackageRemovedInfo removedInfo;
17339        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
17340
17341        public void setError(int code, String msg) {
17342            setReturnCode(code);
17343            setReturnMessage(msg);
17344            Slog.w(TAG, msg);
17345        }
17346
17347        public void setError(String msg, PackageParserException e) {
17348            setReturnCode(e.error);
17349            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17350            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17351            for (int i = 0; i < childCount; i++) {
17352                addedChildPackages.valueAt(i).setError(msg, e);
17353            }
17354            Slog.w(TAG, msg, e);
17355        }
17356
17357        public void setError(String msg, PackageManagerException e) {
17358            returnCode = e.error;
17359            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17360            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17361            for (int i = 0; i < childCount; i++) {
17362                addedChildPackages.valueAt(i).setError(msg, e);
17363            }
17364            Slog.w(TAG, msg, e);
17365        }
17366
17367        public void setReturnCode(int returnCode) {
17368            this.returnCode = returnCode;
17369            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17370            for (int i = 0; i < childCount; i++) {
17371                addedChildPackages.valueAt(i).returnCode = returnCode;
17372            }
17373        }
17374
17375        private void setReturnMessage(String returnMsg) {
17376            this.returnMsg = returnMsg;
17377            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17378            for (int i = 0; i < childCount; i++) {
17379                addedChildPackages.valueAt(i).returnMsg = returnMsg;
17380            }
17381        }
17382
17383        // In some error cases we want to convey more info back to the observer
17384        String origPackage;
17385        String origPermission;
17386    }
17387
17388    /*
17389     * Install a non-existing package.
17390     */
17391    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17392            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17393            PackageInstalledInfo res, int installReason) {
17394        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17395
17396        // Remember this for later, in case we need to rollback this install
17397        String pkgName = pkg.packageName;
17398
17399        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17400
17401        synchronized(mPackages) {
17402            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17403            if (renamedPackage != null) {
17404                // A package with the same name is already installed, though
17405                // it has been renamed to an older name.  The package we
17406                // are trying to install should be installed as an update to
17407                // the existing one, but that has not been requested, so bail.
17408                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17409                        + " without first uninstalling package running as "
17410                        + renamedPackage);
17411                return;
17412            }
17413            if (mPackages.containsKey(pkgName)) {
17414                // Don't allow installation over an existing package with the same name.
17415                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17416                        + " without first uninstalling.");
17417                return;
17418            }
17419        }
17420
17421        try {
17422            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17423                    System.currentTimeMillis(), user);
17424
17425            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17426
17427            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17428                prepareAppDataAfterInstallLIF(newPackage);
17429
17430            } else {
17431                // Remove package from internal structures, but keep around any
17432                // data that might have already existed
17433                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17434                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17435            }
17436        } catch (PackageManagerException e) {
17437            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17438        }
17439
17440        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17441    }
17442
17443    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17444        // Can't rotate keys during boot or if sharedUser.
17445        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17446                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17447            return false;
17448        }
17449        // app is using upgradeKeySets; make sure all are valid
17450        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17451        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17452        for (int i = 0; i < upgradeKeySets.length; i++) {
17453            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17454                Slog.wtf(TAG, "Package "
17455                         + (oldPs.name != null ? oldPs.name : "<null>")
17456                         + " contains upgrade-key-set reference to unknown key-set: "
17457                         + upgradeKeySets[i]
17458                         + " reverting to signatures check.");
17459                return false;
17460            }
17461        }
17462        return true;
17463    }
17464
17465    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17466        // Upgrade keysets are being used.  Determine if new package has a superset of the
17467        // required keys.
17468        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17469        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17470        for (int i = 0; i < upgradeKeySets.length; i++) {
17471            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17472            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17473                return true;
17474            }
17475        }
17476        return false;
17477    }
17478
17479    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17480        try (DigestInputStream digestStream =
17481                new DigestInputStream(new FileInputStream(file), digest)) {
17482            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17483        }
17484    }
17485
17486    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17487            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17488            int installReason) {
17489        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17490
17491        final PackageParser.Package oldPackage;
17492        final PackageSetting ps;
17493        final String pkgName = pkg.packageName;
17494        final int[] allUsers;
17495        final int[] installedUsers;
17496
17497        synchronized(mPackages) {
17498            oldPackage = mPackages.get(pkgName);
17499            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17500
17501            // don't allow upgrade to target a release SDK from a pre-release SDK
17502            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17503                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17504            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17505                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17506            if (oldTargetsPreRelease
17507                    && !newTargetsPreRelease
17508                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17509                Slog.w(TAG, "Can't install package targeting released sdk");
17510                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17511                return;
17512            }
17513
17514            ps = mSettings.mPackages.get(pkgName);
17515
17516            // verify signatures are valid
17517            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17518                if (!checkUpgradeKeySetLP(ps, pkg)) {
17519                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17520                            "New package not signed by keys specified by upgrade-keysets: "
17521                                    + pkgName);
17522                    return;
17523                }
17524            } else {
17525                // default to original signature matching
17526                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17527                        != PackageManager.SIGNATURE_MATCH) {
17528                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17529                            "New package has a different signature: " + pkgName);
17530                    return;
17531                }
17532            }
17533
17534            // don't allow a system upgrade unless the upgrade hash matches
17535            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17536                byte[] digestBytes = null;
17537                try {
17538                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17539                    updateDigest(digest, new File(pkg.baseCodePath));
17540                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17541                        for (String path : pkg.splitCodePaths) {
17542                            updateDigest(digest, new File(path));
17543                        }
17544                    }
17545                    digestBytes = digest.digest();
17546                } catch (NoSuchAlgorithmException | IOException e) {
17547                    res.setError(INSTALL_FAILED_INVALID_APK,
17548                            "Could not compute hash: " + pkgName);
17549                    return;
17550                }
17551                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17552                    res.setError(INSTALL_FAILED_INVALID_APK,
17553                            "New package fails restrict-update check: " + pkgName);
17554                    return;
17555                }
17556                // retain upgrade restriction
17557                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17558            }
17559
17560            // Check for shared user id changes
17561            String invalidPackageName =
17562                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17563            if (invalidPackageName != null) {
17564                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17565                        "Package " + invalidPackageName + " tried to change user "
17566                                + oldPackage.mSharedUserId);
17567                return;
17568            }
17569
17570            // In case of rollback, remember per-user/profile install state
17571            allUsers = sUserManager.getUserIds();
17572            installedUsers = ps.queryInstalledUsers(allUsers, true);
17573
17574            // don't allow an upgrade from full to ephemeral
17575            if (isInstantApp) {
17576                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17577                    for (int currentUser : allUsers) {
17578                        if (!ps.getInstantApp(currentUser)) {
17579                            // can't downgrade from full to instant
17580                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17581                                    + " for user: " + currentUser);
17582                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17583                            return;
17584                        }
17585                    }
17586                } else if (!ps.getInstantApp(user.getIdentifier())) {
17587                    // can't downgrade from full to instant
17588                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17589                            + " for user: " + user.getIdentifier());
17590                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17591                    return;
17592                }
17593            }
17594        }
17595
17596        // Update what is removed
17597        res.removedInfo = new PackageRemovedInfo(this);
17598        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17599        res.removedInfo.removedPackage = oldPackage.packageName;
17600        res.removedInfo.installerPackageName = ps.installerPackageName;
17601        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17602        res.removedInfo.isUpdate = true;
17603        res.removedInfo.origUsers = installedUsers;
17604        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17605        for (int i = 0; i < installedUsers.length; i++) {
17606            final int userId = installedUsers[i];
17607            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17608        }
17609
17610        final int childCount = (oldPackage.childPackages != null)
17611                ? oldPackage.childPackages.size() : 0;
17612        for (int i = 0; i < childCount; i++) {
17613            boolean childPackageUpdated = false;
17614            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17615            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17616            if (res.addedChildPackages != null) {
17617                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17618                if (childRes != null) {
17619                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17620                    childRes.removedInfo.removedPackage = childPkg.packageName;
17621                    if (childPs != null) {
17622                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17623                    }
17624                    childRes.removedInfo.isUpdate = true;
17625                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17626                    childPackageUpdated = true;
17627                }
17628            }
17629            if (!childPackageUpdated) {
17630                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17631                childRemovedRes.removedPackage = childPkg.packageName;
17632                if (childPs != null) {
17633                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17634                }
17635                childRemovedRes.isUpdate = false;
17636                childRemovedRes.dataRemoved = true;
17637                synchronized (mPackages) {
17638                    if (childPs != null) {
17639                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17640                    }
17641                }
17642                if (res.removedInfo.removedChildPackages == null) {
17643                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17644                }
17645                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17646            }
17647        }
17648
17649        boolean sysPkg = (isSystemApp(oldPackage));
17650        if (sysPkg) {
17651            // Set the system/privileged flags as needed
17652            final boolean privileged =
17653                    (oldPackage.applicationInfo.privateFlags
17654                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17655            final int systemPolicyFlags = policyFlags
17656                    | PackageParser.PARSE_IS_SYSTEM
17657                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17658
17659            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17660                    user, allUsers, installerPackageName, res, installReason);
17661        } else {
17662            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17663                    user, allUsers, installerPackageName, res, installReason);
17664        }
17665    }
17666
17667    @Override
17668    public List<String> getPreviousCodePaths(String packageName) {
17669        final int callingUid = Binder.getCallingUid();
17670        final List<String> result = new ArrayList<>();
17671        if (getInstantAppPackageName(callingUid) != null) {
17672            return result;
17673        }
17674        final PackageSetting ps = mSettings.mPackages.get(packageName);
17675        if (ps != null
17676                && ps.oldCodePaths != null
17677                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17678            result.addAll(ps.oldCodePaths);
17679        }
17680        return result;
17681    }
17682
17683    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17684            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17685            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17686            int installReason) {
17687        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17688                + deletedPackage);
17689
17690        String pkgName = deletedPackage.packageName;
17691        boolean deletedPkg = true;
17692        boolean addedPkg = false;
17693        boolean updatedSettings = false;
17694        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17695        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17696                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17697
17698        final long origUpdateTime = (pkg.mExtras != null)
17699                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17700
17701        // First delete the existing package while retaining the data directory
17702        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17703                res.removedInfo, true, pkg)) {
17704            // If the existing package wasn't successfully deleted
17705            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17706            deletedPkg = false;
17707        } else {
17708            // Successfully deleted the old package; proceed with replace.
17709
17710            // If deleted package lived in a container, give users a chance to
17711            // relinquish resources before killing.
17712            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17713                if (DEBUG_INSTALL) {
17714                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17715                }
17716                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17717                final ArrayList<String> pkgList = new ArrayList<String>(1);
17718                pkgList.add(deletedPackage.applicationInfo.packageName);
17719                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17720            }
17721
17722            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17723                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17724            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17725
17726            try {
17727                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17728                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17729                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17730                        installReason);
17731
17732                // Update the in-memory copy of the previous code paths.
17733                PackageSetting ps = mSettings.mPackages.get(pkgName);
17734                if (!killApp) {
17735                    if (ps.oldCodePaths == null) {
17736                        ps.oldCodePaths = new ArraySet<>();
17737                    }
17738                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17739                    if (deletedPackage.splitCodePaths != null) {
17740                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17741                    }
17742                } else {
17743                    ps.oldCodePaths = null;
17744                }
17745                if (ps.childPackageNames != null) {
17746                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17747                        final String childPkgName = ps.childPackageNames.get(i);
17748                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17749                        childPs.oldCodePaths = ps.oldCodePaths;
17750                    }
17751                }
17752                // set instant app status, but, only if it's explicitly specified
17753                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17754                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17755                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17756                prepareAppDataAfterInstallLIF(newPackage);
17757                addedPkg = true;
17758                mDexManager.notifyPackageUpdated(newPackage.packageName,
17759                        newPackage.baseCodePath, newPackage.splitCodePaths);
17760            } catch (PackageManagerException e) {
17761                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17762            }
17763        }
17764
17765        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17766            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17767
17768            // Revert all internal state mutations and added folders for the failed install
17769            if (addedPkg) {
17770                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17771                        res.removedInfo, true, null);
17772            }
17773
17774            // Restore the old package
17775            if (deletedPkg) {
17776                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17777                File restoreFile = new File(deletedPackage.codePath);
17778                // Parse old package
17779                boolean oldExternal = isExternal(deletedPackage);
17780                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17781                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17782                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17783                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17784                try {
17785                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17786                            null);
17787                } catch (PackageManagerException e) {
17788                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17789                            + e.getMessage());
17790                    return;
17791                }
17792
17793                synchronized (mPackages) {
17794                    // Ensure the installer package name up to date
17795                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17796
17797                    // Update permissions for restored package
17798                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17799
17800                    mSettings.writeLPr();
17801                }
17802
17803                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17804            }
17805        } else {
17806            synchronized (mPackages) {
17807                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17808                if (ps != null) {
17809                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17810                    if (res.removedInfo.removedChildPackages != null) {
17811                        final int childCount = res.removedInfo.removedChildPackages.size();
17812                        // Iterate in reverse as we may modify the collection
17813                        for (int i = childCount - 1; i >= 0; i--) {
17814                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17815                            if (res.addedChildPackages.containsKey(childPackageName)) {
17816                                res.removedInfo.removedChildPackages.removeAt(i);
17817                            } else {
17818                                PackageRemovedInfo childInfo = res.removedInfo
17819                                        .removedChildPackages.valueAt(i);
17820                                childInfo.removedForAllUsers = mPackages.get(
17821                                        childInfo.removedPackage) == null;
17822                            }
17823                        }
17824                    }
17825                }
17826            }
17827        }
17828    }
17829
17830    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17831            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17832            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17833            int installReason) {
17834        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17835                + ", old=" + deletedPackage);
17836
17837        final boolean disabledSystem;
17838
17839        // Remove existing system package
17840        removePackageLI(deletedPackage, true);
17841
17842        synchronized (mPackages) {
17843            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17844        }
17845        if (!disabledSystem) {
17846            // We didn't need to disable the .apk as a current system package,
17847            // which means we are replacing another update that is already
17848            // installed.  We need to make sure to delete the older one's .apk.
17849            res.removedInfo.args = createInstallArgsForExisting(0,
17850                    deletedPackage.applicationInfo.getCodePath(),
17851                    deletedPackage.applicationInfo.getResourcePath(),
17852                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17853        } else {
17854            res.removedInfo.args = null;
17855        }
17856
17857        // Successfully disabled the old package. Now proceed with re-installation
17858        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17859                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17860        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17861
17862        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17863        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17864                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17865
17866        PackageParser.Package newPackage = null;
17867        try {
17868            // Add the package to the internal data structures
17869            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17870
17871            // Set the update and install times
17872            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17873            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17874                    System.currentTimeMillis());
17875
17876            // Update the package dynamic state if succeeded
17877            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17878                // Now that the install succeeded make sure we remove data
17879                // directories for any child package the update removed.
17880                final int deletedChildCount = (deletedPackage.childPackages != null)
17881                        ? deletedPackage.childPackages.size() : 0;
17882                final int newChildCount = (newPackage.childPackages != null)
17883                        ? newPackage.childPackages.size() : 0;
17884                for (int i = 0; i < deletedChildCount; i++) {
17885                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17886                    boolean childPackageDeleted = true;
17887                    for (int j = 0; j < newChildCount; j++) {
17888                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17889                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17890                            childPackageDeleted = false;
17891                            break;
17892                        }
17893                    }
17894                    if (childPackageDeleted) {
17895                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17896                                deletedChildPkg.packageName);
17897                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17898                            PackageRemovedInfo removedChildRes = res.removedInfo
17899                                    .removedChildPackages.get(deletedChildPkg.packageName);
17900                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17901                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17902                        }
17903                    }
17904                }
17905
17906                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17907                        installReason);
17908                prepareAppDataAfterInstallLIF(newPackage);
17909
17910                mDexManager.notifyPackageUpdated(newPackage.packageName,
17911                            newPackage.baseCodePath, newPackage.splitCodePaths);
17912            }
17913        } catch (PackageManagerException e) {
17914            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17915            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17916        }
17917
17918        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17919            // Re installation failed. Restore old information
17920            // Remove new pkg information
17921            if (newPackage != null) {
17922                removeInstalledPackageLI(newPackage, true);
17923            }
17924            // Add back the old system package
17925            try {
17926                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17927            } catch (PackageManagerException e) {
17928                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17929            }
17930
17931            synchronized (mPackages) {
17932                if (disabledSystem) {
17933                    enableSystemPackageLPw(deletedPackage);
17934                }
17935
17936                // Ensure the installer package name up to date
17937                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17938
17939                // Update permissions for restored package
17940                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17941
17942                mSettings.writeLPr();
17943            }
17944
17945            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17946                    + " after failed upgrade");
17947        }
17948    }
17949
17950    /**
17951     * Checks whether the parent or any of the child packages have a change shared
17952     * user. For a package to be a valid update the shred users of the parent and
17953     * the children should match. We may later support changing child shared users.
17954     * @param oldPkg The updated package.
17955     * @param newPkg The update package.
17956     * @return The shared user that change between the versions.
17957     */
17958    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17959            PackageParser.Package newPkg) {
17960        // Check parent shared user
17961        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17962            return newPkg.packageName;
17963        }
17964        // Check child shared users
17965        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17966        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17967        for (int i = 0; i < newChildCount; i++) {
17968            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17969            // If this child was present, did it have the same shared user?
17970            for (int j = 0; j < oldChildCount; j++) {
17971                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17972                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17973                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17974                    return newChildPkg.packageName;
17975                }
17976            }
17977        }
17978        return null;
17979    }
17980
17981    private void removeNativeBinariesLI(PackageSetting ps) {
17982        // Remove the lib path for the parent package
17983        if (ps != null) {
17984            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17985            // Remove the lib path for the child packages
17986            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17987            for (int i = 0; i < childCount; i++) {
17988                PackageSetting childPs = null;
17989                synchronized (mPackages) {
17990                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17991                }
17992                if (childPs != null) {
17993                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17994                            .legacyNativeLibraryPathString);
17995                }
17996            }
17997        }
17998    }
17999
18000    private void enableSystemPackageLPw(PackageParser.Package pkg) {
18001        // Enable the parent package
18002        mSettings.enableSystemPackageLPw(pkg.packageName);
18003        // Enable the child packages
18004        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18005        for (int i = 0; i < childCount; i++) {
18006            PackageParser.Package childPkg = pkg.childPackages.get(i);
18007            mSettings.enableSystemPackageLPw(childPkg.packageName);
18008        }
18009    }
18010
18011    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
18012            PackageParser.Package newPkg) {
18013        // Disable the parent package (parent always replaced)
18014        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
18015        // Disable the child packages
18016        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
18017        for (int i = 0; i < childCount; i++) {
18018            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
18019            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
18020            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
18021        }
18022        return disabled;
18023    }
18024
18025    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
18026            String installerPackageName) {
18027        // Enable the parent package
18028        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
18029        // Enable the child packages
18030        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18031        for (int i = 0; i < childCount; i++) {
18032            PackageParser.Package childPkg = pkg.childPackages.get(i);
18033            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
18034        }
18035    }
18036
18037    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
18038        // Collect all used permissions in the UID
18039        ArraySet<String> usedPermissions = new ArraySet<>();
18040        final int packageCount = su.packages.size();
18041        for (int i = 0; i < packageCount; i++) {
18042            PackageSetting ps = su.packages.valueAt(i);
18043            if (ps.pkg == null) {
18044                continue;
18045            }
18046            final int requestedPermCount = ps.pkg.requestedPermissions.size();
18047            for (int j = 0; j < requestedPermCount; j++) {
18048                String permission = ps.pkg.requestedPermissions.get(j);
18049                BasePermission bp = mSettings.mPermissions.get(permission);
18050                if (bp != null) {
18051                    usedPermissions.add(permission);
18052                }
18053            }
18054        }
18055
18056        PermissionsState permissionsState = su.getPermissionsState();
18057        // Prune install permissions
18058        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
18059        final int installPermCount = installPermStates.size();
18060        for (int i = installPermCount - 1; i >= 0;  i--) {
18061            PermissionState permissionState = installPermStates.get(i);
18062            if (!usedPermissions.contains(permissionState.getName())) {
18063                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18064                if (bp != null) {
18065                    permissionsState.revokeInstallPermission(bp);
18066                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
18067                            PackageManager.MASK_PERMISSION_FLAGS, 0);
18068                }
18069            }
18070        }
18071
18072        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
18073
18074        // Prune runtime permissions
18075        for (int userId : allUserIds) {
18076            List<PermissionState> runtimePermStates = permissionsState
18077                    .getRuntimePermissionStates(userId);
18078            final int runtimePermCount = runtimePermStates.size();
18079            for (int i = runtimePermCount - 1; i >= 0; i--) {
18080                PermissionState permissionState = runtimePermStates.get(i);
18081                if (!usedPermissions.contains(permissionState.getName())) {
18082                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18083                    if (bp != null) {
18084                        permissionsState.revokeRuntimePermission(bp, userId);
18085                        permissionsState.updatePermissionFlags(bp, userId,
18086                                PackageManager.MASK_PERMISSION_FLAGS, 0);
18087                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
18088                                runtimePermissionChangedUserIds, userId);
18089                    }
18090                }
18091            }
18092        }
18093
18094        return runtimePermissionChangedUserIds;
18095    }
18096
18097    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
18098            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
18099        // Update the parent package setting
18100        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
18101                res, user, installReason);
18102        // Update the child packages setting
18103        final int childCount = (newPackage.childPackages != null)
18104                ? newPackage.childPackages.size() : 0;
18105        for (int i = 0; i < childCount; i++) {
18106            PackageParser.Package childPackage = newPackage.childPackages.get(i);
18107            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
18108            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
18109                    childRes.origUsers, childRes, user, installReason);
18110        }
18111    }
18112
18113    private void updateSettingsInternalLI(PackageParser.Package newPackage,
18114            String installerPackageName, int[] allUsers, int[] installedForUsers,
18115            PackageInstalledInfo res, UserHandle user, int installReason) {
18116        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
18117
18118        String pkgName = newPackage.packageName;
18119        synchronized (mPackages) {
18120            //write settings. the installStatus will be incomplete at this stage.
18121            //note that the new package setting would have already been
18122            //added to mPackages. It hasn't been persisted yet.
18123            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
18124            // TODO: Remove this write? It's also written at the end of this method
18125            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18126            mSettings.writeLPr();
18127            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18128        }
18129
18130        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
18131        synchronized (mPackages) {
18132            updatePermissionsLPw(newPackage.packageName, newPackage,
18133                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
18134                            ? UPDATE_PERMISSIONS_ALL : 0));
18135            // For system-bundled packages, we assume that installing an upgraded version
18136            // of the package implies that the user actually wants to run that new code,
18137            // so we enable the package.
18138            PackageSetting ps = mSettings.mPackages.get(pkgName);
18139            final int userId = user.getIdentifier();
18140            if (ps != null) {
18141                if (isSystemApp(newPackage)) {
18142                    if (DEBUG_INSTALL) {
18143                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
18144                    }
18145                    // Enable system package for requested users
18146                    if (res.origUsers != null) {
18147                        for (int origUserId : res.origUsers) {
18148                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
18149                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
18150                                        origUserId, installerPackageName);
18151                            }
18152                        }
18153                    }
18154                    // Also convey the prior install/uninstall state
18155                    if (allUsers != null && installedForUsers != null) {
18156                        for (int currentUserId : allUsers) {
18157                            final boolean installed = ArrayUtils.contains(
18158                                    installedForUsers, currentUserId);
18159                            if (DEBUG_INSTALL) {
18160                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
18161                            }
18162                            ps.setInstalled(installed, currentUserId);
18163                        }
18164                        // these install state changes will be persisted in the
18165                        // upcoming call to mSettings.writeLPr().
18166                    }
18167                }
18168                // It's implied that when a user requests installation, they want the app to be
18169                // installed and enabled.
18170                if (userId != UserHandle.USER_ALL) {
18171                    ps.setInstalled(true, userId);
18172                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
18173                }
18174
18175                // When replacing an existing package, preserve the original install reason for all
18176                // users that had the package installed before.
18177                final Set<Integer> previousUserIds = new ArraySet<>();
18178                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
18179                    final int installReasonCount = res.removedInfo.installReasons.size();
18180                    for (int i = 0; i < installReasonCount; i++) {
18181                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
18182                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
18183                        ps.setInstallReason(previousInstallReason, previousUserId);
18184                        previousUserIds.add(previousUserId);
18185                    }
18186                }
18187
18188                // Set install reason for users that are having the package newly installed.
18189                if (userId == UserHandle.USER_ALL) {
18190                    for (int currentUserId : sUserManager.getUserIds()) {
18191                        if (!previousUserIds.contains(currentUserId)) {
18192                            ps.setInstallReason(installReason, currentUserId);
18193                        }
18194                    }
18195                } else if (!previousUserIds.contains(userId)) {
18196                    ps.setInstallReason(installReason, userId);
18197                }
18198                mSettings.writeKernelMappingLPr(ps);
18199            }
18200            res.name = pkgName;
18201            res.uid = newPackage.applicationInfo.uid;
18202            res.pkg = newPackage;
18203            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
18204            mSettings.setInstallerPackageName(pkgName, installerPackageName);
18205            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18206            //to update install status
18207            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18208            mSettings.writeLPr();
18209            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18210        }
18211
18212        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18213    }
18214
18215    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
18216        try {
18217            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
18218            installPackageLI(args, res);
18219        } finally {
18220            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18221        }
18222    }
18223
18224    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
18225        final int installFlags = args.installFlags;
18226        final String installerPackageName = args.installerPackageName;
18227        final String volumeUuid = args.volumeUuid;
18228        final File tmpPackageFile = new File(args.getCodePath());
18229        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
18230        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
18231                || (args.volumeUuid != null));
18232        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
18233        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
18234        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
18235        final boolean virtualPreload =
18236                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
18237        boolean replace = false;
18238        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
18239        if (args.move != null) {
18240            // moving a complete application; perform an initial scan on the new install location
18241            scanFlags |= SCAN_INITIAL;
18242        }
18243        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
18244            scanFlags |= SCAN_DONT_KILL_APP;
18245        }
18246        if (instantApp) {
18247            scanFlags |= SCAN_AS_INSTANT_APP;
18248        }
18249        if (fullApp) {
18250            scanFlags |= SCAN_AS_FULL_APP;
18251        }
18252        if (virtualPreload) {
18253            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
18254        }
18255
18256        // Result object to be returned
18257        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18258        res.installerPackageName = installerPackageName;
18259
18260        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
18261
18262        // Sanity check
18263        if (instantApp && (forwardLocked || onExternal)) {
18264            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
18265                    + " external=" + onExternal);
18266            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
18267            return;
18268        }
18269
18270        // Retrieve PackageSettings and parse package
18271        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
18272                | PackageParser.PARSE_ENFORCE_CODE
18273                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
18274                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
18275                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
18276                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
18277        PackageParser pp = new PackageParser();
18278        pp.setSeparateProcesses(mSeparateProcesses);
18279        pp.setDisplayMetrics(mMetrics);
18280        pp.setCallback(mPackageParserCallback);
18281
18282        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
18283        final PackageParser.Package pkg;
18284        try {
18285            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
18286        } catch (PackageParserException e) {
18287            res.setError("Failed parse during installPackageLI", e);
18288            return;
18289        } finally {
18290            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18291        }
18292
18293        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
18294        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
18295            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
18296            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18297                    "Instant app package must target O");
18298            return;
18299        }
18300        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
18301            Slog.w(TAG, "Instant app package " + pkg.packageName
18302                    + " does not target targetSandboxVersion 2");
18303            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18304                    "Instant app package must use targetSanboxVersion 2");
18305            return;
18306        }
18307
18308        if (pkg.applicationInfo.isStaticSharedLibrary()) {
18309            // Static shared libraries have synthetic package names
18310            renameStaticSharedLibraryPackage(pkg);
18311
18312            // No static shared libs on external storage
18313            if (onExternal) {
18314                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
18315                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18316                        "Packages declaring static-shared libs cannot be updated");
18317                return;
18318            }
18319        }
18320
18321        // If we are installing a clustered package add results for the children
18322        if (pkg.childPackages != null) {
18323            synchronized (mPackages) {
18324                final int childCount = pkg.childPackages.size();
18325                for (int i = 0; i < childCount; i++) {
18326                    PackageParser.Package childPkg = pkg.childPackages.get(i);
18327                    PackageInstalledInfo childRes = new PackageInstalledInfo();
18328                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18329                    childRes.pkg = childPkg;
18330                    childRes.name = childPkg.packageName;
18331                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18332                    if (childPs != null) {
18333                        childRes.origUsers = childPs.queryInstalledUsers(
18334                                sUserManager.getUserIds(), true);
18335                    }
18336                    if ((mPackages.containsKey(childPkg.packageName))) {
18337                        childRes.removedInfo = new PackageRemovedInfo(this);
18338                        childRes.removedInfo.removedPackage = childPkg.packageName;
18339                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
18340                    }
18341                    if (res.addedChildPackages == null) {
18342                        res.addedChildPackages = new ArrayMap<>();
18343                    }
18344                    res.addedChildPackages.put(childPkg.packageName, childRes);
18345                }
18346            }
18347        }
18348
18349        // If package doesn't declare API override, mark that we have an install
18350        // time CPU ABI override.
18351        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
18352            pkg.cpuAbiOverride = args.abiOverride;
18353        }
18354
18355        String pkgName = res.name = pkg.packageName;
18356        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
18357            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
18358                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
18359                return;
18360            }
18361        }
18362
18363        try {
18364            // either use what we've been given or parse directly from the APK
18365            if (args.certificates != null) {
18366                try {
18367                    PackageParser.populateCertificates(pkg, args.certificates);
18368                } catch (PackageParserException e) {
18369                    // there was something wrong with the certificates we were given;
18370                    // try to pull them from the APK
18371                    PackageParser.collectCertificates(pkg, parseFlags);
18372                }
18373            } else {
18374                PackageParser.collectCertificates(pkg, parseFlags);
18375            }
18376        } catch (PackageParserException e) {
18377            res.setError("Failed collect during installPackageLI", e);
18378            return;
18379        }
18380
18381        // Get rid of all references to package scan path via parser.
18382        pp = null;
18383        String oldCodePath = null;
18384        boolean systemApp = false;
18385        synchronized (mPackages) {
18386            // Check if installing already existing package
18387            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18388                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18389                if (pkg.mOriginalPackages != null
18390                        && pkg.mOriginalPackages.contains(oldName)
18391                        && mPackages.containsKey(oldName)) {
18392                    // This package is derived from an original package,
18393                    // and this device has been updating from that original
18394                    // name.  We must continue using the original name, so
18395                    // rename the new package here.
18396                    pkg.setPackageName(oldName);
18397                    pkgName = pkg.packageName;
18398                    replace = true;
18399                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18400                            + oldName + " pkgName=" + pkgName);
18401                } else if (mPackages.containsKey(pkgName)) {
18402                    // This package, under its official name, already exists
18403                    // on the device; we should replace it.
18404                    replace = true;
18405                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18406                }
18407
18408                // Child packages are installed through the parent package
18409                if (pkg.parentPackage != null) {
18410                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18411                            "Package " + pkg.packageName + " is child of package "
18412                                    + pkg.parentPackage.parentPackage + ". Child packages "
18413                                    + "can be updated only through the parent package.");
18414                    return;
18415                }
18416
18417                if (replace) {
18418                    // Prevent apps opting out from runtime permissions
18419                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18420                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18421                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18422                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18423                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18424                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18425                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18426                                        + " doesn't support runtime permissions but the old"
18427                                        + " target SDK " + oldTargetSdk + " does.");
18428                        return;
18429                    }
18430                    // Prevent apps from downgrading their targetSandbox.
18431                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18432                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18433                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18434                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18435                                "Package " + pkg.packageName + " new target sandbox "
18436                                + newTargetSandbox + " is incompatible with the previous value of"
18437                                + oldTargetSandbox + ".");
18438                        return;
18439                    }
18440
18441                    // Prevent installing of child packages
18442                    if (oldPackage.parentPackage != null) {
18443                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18444                                "Package " + pkg.packageName + " is child of package "
18445                                        + oldPackage.parentPackage + ". Child packages "
18446                                        + "can be updated only through the parent package.");
18447                        return;
18448                    }
18449                }
18450            }
18451
18452            PackageSetting ps = mSettings.mPackages.get(pkgName);
18453            if (ps != null) {
18454                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18455
18456                // Static shared libs have same package with different versions where
18457                // we internally use a synthetic package name to allow multiple versions
18458                // of the same package, therefore we need to compare signatures against
18459                // the package setting for the latest library version.
18460                PackageSetting signatureCheckPs = ps;
18461                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18462                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18463                    if (libraryEntry != null) {
18464                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18465                    }
18466                }
18467
18468                // Quick sanity check that we're signed correctly if updating;
18469                // we'll check this again later when scanning, but we want to
18470                // bail early here before tripping over redefined permissions.
18471                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18472                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18473                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18474                                + pkg.packageName + " upgrade keys do not match the "
18475                                + "previously installed version");
18476                        return;
18477                    }
18478                } else {
18479                    try {
18480                        verifySignaturesLP(signatureCheckPs, pkg);
18481                    } catch (PackageManagerException e) {
18482                        res.setError(e.error, e.getMessage());
18483                        return;
18484                    }
18485                }
18486
18487                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18488                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18489                    systemApp = (ps.pkg.applicationInfo.flags &
18490                            ApplicationInfo.FLAG_SYSTEM) != 0;
18491                }
18492                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18493            }
18494
18495            int N = pkg.permissions.size();
18496            for (int i = N-1; i >= 0; i--) {
18497                PackageParser.Permission perm = pkg.permissions.get(i);
18498                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18499
18500                // Don't allow anyone but the system to define ephemeral permissions.
18501                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
18502                        && !systemApp) {
18503                    Slog.w(TAG, "Non-System package " + pkg.packageName
18504                            + " attempting to delcare ephemeral permission "
18505                            + perm.info.name + "; Removing ephemeral.");
18506                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
18507                }
18508                // Check whether the newly-scanned package wants to define an already-defined perm
18509                if (bp != null) {
18510                    // If the defining package is signed with our cert, it's okay.  This
18511                    // also includes the "updating the same package" case, of course.
18512                    // "updating same package" could also involve key-rotation.
18513                    final boolean sigsOk;
18514                    if (bp.sourcePackage.equals(pkg.packageName)
18515                            && (bp.packageSetting instanceof PackageSetting)
18516                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18517                                    scanFlags))) {
18518                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18519                    } else {
18520                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18521                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18522                    }
18523                    if (!sigsOk) {
18524                        // If the owning package is the system itself, we log but allow
18525                        // install to proceed; we fail the install on all other permission
18526                        // redefinitions.
18527                        if (!bp.sourcePackage.equals("android")) {
18528                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18529                                    + pkg.packageName + " attempting to redeclare permission "
18530                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18531                            res.origPermission = perm.info.name;
18532                            res.origPackage = bp.sourcePackage;
18533                            return;
18534                        } else {
18535                            Slog.w(TAG, "Package " + pkg.packageName
18536                                    + " attempting to redeclare system permission "
18537                                    + perm.info.name + "; ignoring new declaration");
18538                            pkg.permissions.remove(i);
18539                        }
18540                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18541                        // Prevent apps to change protection level to dangerous from any other
18542                        // type as this would allow a privilege escalation where an app adds a
18543                        // normal/signature permission in other app's group and later redefines
18544                        // it as dangerous leading to the group auto-grant.
18545                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18546                                == PermissionInfo.PROTECTION_DANGEROUS) {
18547                            if (bp != null && !bp.isRuntime()) {
18548                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18549                                        + "non-runtime permission " + perm.info.name
18550                                        + " to runtime; keeping old protection level");
18551                                perm.info.protectionLevel = bp.protectionLevel;
18552                            }
18553                        }
18554                    }
18555                }
18556            }
18557        }
18558
18559        if (systemApp) {
18560            if (onExternal) {
18561                // Abort update; system app can't be replaced with app on sdcard
18562                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18563                        "Cannot install updates to system apps on sdcard");
18564                return;
18565            } else if (instantApp) {
18566                // Abort update; system app can't be replaced with an instant app
18567                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18568                        "Cannot update a system app with an instant app");
18569                return;
18570            }
18571        }
18572
18573        if (args.move != null) {
18574            // We did an in-place move, so dex is ready to roll
18575            scanFlags |= SCAN_NO_DEX;
18576            scanFlags |= SCAN_MOVE;
18577
18578            synchronized (mPackages) {
18579                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18580                if (ps == null) {
18581                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18582                            "Missing settings for moved package " + pkgName);
18583                }
18584
18585                // We moved the entire application as-is, so bring over the
18586                // previously derived ABI information.
18587                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18588                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18589            }
18590
18591        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18592            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18593            scanFlags |= SCAN_NO_DEX;
18594
18595            try {
18596                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18597                    args.abiOverride : pkg.cpuAbiOverride);
18598                final boolean extractNativeLibs = !pkg.isLibrary();
18599                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18600                        extractNativeLibs, mAppLib32InstallDir);
18601            } catch (PackageManagerException pme) {
18602                Slog.e(TAG, "Error deriving application ABI", pme);
18603                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18604                return;
18605            }
18606
18607            // Shared libraries for the package need to be updated.
18608            synchronized (mPackages) {
18609                try {
18610                    updateSharedLibrariesLPr(pkg, null);
18611                } catch (PackageManagerException e) {
18612                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18613                }
18614            }
18615
18616            // dexopt can take some time to complete, so, for instant apps, we skip this
18617            // step during installation. Instead, we'll take extra time the first time the
18618            // instant app starts. It's preferred to do it this way to provide continuous
18619            // progress to the user instead of mysteriously blocking somewhere in the
18620            // middle of running an instant app. The default behaviour can be overridden
18621            // via gservices.
18622            if (!instantApp || Global.getInt(
18623                        mContext.getContentResolver(), Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0) {
18624                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18625                // Do not run PackageDexOptimizer through the local performDexOpt
18626                // method because `pkg` may not be in `mPackages` yet.
18627                //
18628                // Also, don't fail application installs if the dexopt step fails.
18629                DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
18630                        REASON_INSTALL,
18631                        DexoptOptions.DEXOPT_BOOT_COMPLETE);
18632                mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18633                        null /* instructionSets */,
18634                        getOrCreateCompilerPackageStats(pkg),
18635                        mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
18636                        dexoptOptions);
18637                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18638            }
18639
18640            // Notify BackgroundDexOptService that the package has been changed.
18641            // If this is an update of a package which used to fail to compile,
18642            // BDOS will remove it from its blacklist.
18643            // TODO: Layering violation
18644            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18645        }
18646
18647        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18648            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18649            return;
18650        }
18651
18652        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18653
18654        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18655                "installPackageLI")) {
18656            if (replace) {
18657                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18658                    // Static libs have a synthetic package name containing the version
18659                    // and cannot be updated as an update would get a new package name,
18660                    // unless this is the exact same version code which is useful for
18661                    // development.
18662                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18663                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18664                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18665                                + "static-shared libs cannot be updated");
18666                        return;
18667                    }
18668                }
18669                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18670                        installerPackageName, res, args.installReason);
18671            } else {
18672                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18673                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18674            }
18675        }
18676
18677        synchronized (mPackages) {
18678            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18679            if (ps != null) {
18680                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18681                ps.setUpdateAvailable(false /*updateAvailable*/);
18682            }
18683
18684            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18685            for (int i = 0; i < childCount; i++) {
18686                PackageParser.Package childPkg = pkg.childPackages.get(i);
18687                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18688                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18689                if (childPs != null) {
18690                    childRes.newUsers = childPs.queryInstalledUsers(
18691                            sUserManager.getUserIds(), true);
18692                }
18693            }
18694
18695            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18696                updateSequenceNumberLP(ps, res.newUsers);
18697                updateInstantAppInstallerLocked(pkgName);
18698            }
18699        }
18700    }
18701
18702    private void startIntentFilterVerifications(int userId, boolean replacing,
18703            PackageParser.Package pkg) {
18704        if (mIntentFilterVerifierComponent == null) {
18705            Slog.w(TAG, "No IntentFilter verification will not be done as "
18706                    + "there is no IntentFilterVerifier available!");
18707            return;
18708        }
18709
18710        final int verifierUid = getPackageUid(
18711                mIntentFilterVerifierComponent.getPackageName(),
18712                MATCH_DEBUG_TRIAGED_MISSING,
18713                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18714
18715        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18716        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18717        mHandler.sendMessage(msg);
18718
18719        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18720        for (int i = 0; i < childCount; i++) {
18721            PackageParser.Package childPkg = pkg.childPackages.get(i);
18722            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18723            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18724            mHandler.sendMessage(msg);
18725        }
18726    }
18727
18728    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18729            PackageParser.Package pkg) {
18730        int size = pkg.activities.size();
18731        if (size == 0) {
18732            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18733                    "No activity, so no need to verify any IntentFilter!");
18734            return;
18735        }
18736
18737        final boolean hasDomainURLs = hasDomainURLs(pkg);
18738        if (!hasDomainURLs) {
18739            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18740                    "No domain URLs, so no need to verify any IntentFilter!");
18741            return;
18742        }
18743
18744        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18745                + " if any IntentFilter from the " + size
18746                + " Activities needs verification ...");
18747
18748        int count = 0;
18749        final String packageName = pkg.packageName;
18750
18751        synchronized (mPackages) {
18752            // If this is a new install and we see that we've already run verification for this
18753            // package, we have nothing to do: it means the state was restored from backup.
18754            if (!replacing) {
18755                IntentFilterVerificationInfo ivi =
18756                        mSettings.getIntentFilterVerificationLPr(packageName);
18757                if (ivi != null) {
18758                    if (DEBUG_DOMAIN_VERIFICATION) {
18759                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18760                                + ivi.getStatusString());
18761                    }
18762                    return;
18763                }
18764            }
18765
18766            // If any filters need to be verified, then all need to be.
18767            boolean needToVerify = false;
18768            for (PackageParser.Activity a : pkg.activities) {
18769                for (ActivityIntentInfo filter : a.intents) {
18770                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18771                        if (DEBUG_DOMAIN_VERIFICATION) {
18772                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18773                        }
18774                        needToVerify = true;
18775                        break;
18776                    }
18777                }
18778            }
18779
18780            if (needToVerify) {
18781                final int verificationId = mIntentFilterVerificationToken++;
18782                for (PackageParser.Activity a : pkg.activities) {
18783                    for (ActivityIntentInfo filter : a.intents) {
18784                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18785                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18786                                    "Verification needed for IntentFilter:" + filter.toString());
18787                            mIntentFilterVerifier.addOneIntentFilterVerification(
18788                                    verifierUid, userId, verificationId, filter, packageName);
18789                            count++;
18790                        }
18791                    }
18792                }
18793            }
18794        }
18795
18796        if (count > 0) {
18797            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18798                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18799                    +  " for userId:" + userId);
18800            mIntentFilterVerifier.startVerifications(userId);
18801        } else {
18802            if (DEBUG_DOMAIN_VERIFICATION) {
18803                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18804            }
18805        }
18806    }
18807
18808    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18809        final ComponentName cn  = filter.activity.getComponentName();
18810        final String packageName = cn.getPackageName();
18811
18812        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18813                packageName);
18814        if (ivi == null) {
18815            return true;
18816        }
18817        int status = ivi.getStatus();
18818        switch (status) {
18819            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18820            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18821                return true;
18822
18823            default:
18824                // Nothing to do
18825                return false;
18826        }
18827    }
18828
18829    private static boolean isMultiArch(ApplicationInfo info) {
18830        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18831    }
18832
18833    private static boolean isExternal(PackageParser.Package pkg) {
18834        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18835    }
18836
18837    private static boolean isExternal(PackageSetting ps) {
18838        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18839    }
18840
18841    private static boolean isSystemApp(PackageParser.Package pkg) {
18842        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18843    }
18844
18845    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18846        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18847    }
18848
18849    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18850        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18851    }
18852
18853    private static boolean isSystemApp(PackageSetting ps) {
18854        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18855    }
18856
18857    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18858        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18859    }
18860
18861    private int packageFlagsToInstallFlags(PackageSetting ps) {
18862        int installFlags = 0;
18863        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18864            // This existing package was an external ASEC install when we have
18865            // the external flag without a UUID
18866            installFlags |= PackageManager.INSTALL_EXTERNAL;
18867        }
18868        if (ps.isForwardLocked()) {
18869            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18870        }
18871        return installFlags;
18872    }
18873
18874    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18875        if (isExternal(pkg)) {
18876            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18877                return StorageManager.UUID_PRIMARY_PHYSICAL;
18878            } else {
18879                return pkg.volumeUuid;
18880            }
18881        } else {
18882            return StorageManager.UUID_PRIVATE_INTERNAL;
18883        }
18884    }
18885
18886    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18887        if (isExternal(pkg)) {
18888            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18889                return mSettings.getExternalVersion();
18890            } else {
18891                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18892            }
18893        } else {
18894            return mSettings.getInternalVersion();
18895        }
18896    }
18897
18898    private void deleteTempPackageFiles() {
18899        final FilenameFilter filter = new FilenameFilter() {
18900            public boolean accept(File dir, String name) {
18901                return name.startsWith("vmdl") && name.endsWith(".tmp");
18902            }
18903        };
18904        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18905            file.delete();
18906        }
18907    }
18908
18909    @Override
18910    public void deletePackageAsUser(String packageName, int versionCode,
18911            IPackageDeleteObserver observer, int userId, int flags) {
18912        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18913                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18914    }
18915
18916    @Override
18917    public void deletePackageVersioned(VersionedPackage versionedPackage,
18918            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18919        final int callingUid = Binder.getCallingUid();
18920        mContext.enforceCallingOrSelfPermission(
18921                android.Manifest.permission.DELETE_PACKAGES, null);
18922        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18923        Preconditions.checkNotNull(versionedPackage);
18924        Preconditions.checkNotNull(observer);
18925        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18926                PackageManager.VERSION_CODE_HIGHEST,
18927                Integer.MAX_VALUE, "versionCode must be >= -1");
18928
18929        final String packageName = versionedPackage.getPackageName();
18930        final int versionCode = versionedPackage.getVersionCode();
18931        final String internalPackageName;
18932        synchronized (mPackages) {
18933            // Normalize package name to handle renamed packages and static libs
18934            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18935                    versionedPackage.getVersionCode());
18936        }
18937
18938        final int uid = Binder.getCallingUid();
18939        if (!isOrphaned(internalPackageName)
18940                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18941            try {
18942                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18943                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18944                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18945                observer.onUserActionRequired(intent);
18946            } catch (RemoteException re) {
18947            }
18948            return;
18949        }
18950        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18951        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18952        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18953            mContext.enforceCallingOrSelfPermission(
18954                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18955                    "deletePackage for user " + userId);
18956        }
18957
18958        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18959            try {
18960                observer.onPackageDeleted(packageName,
18961                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18962            } catch (RemoteException re) {
18963            }
18964            return;
18965        }
18966
18967        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18968            try {
18969                observer.onPackageDeleted(packageName,
18970                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18971            } catch (RemoteException re) {
18972            }
18973            return;
18974        }
18975
18976        if (DEBUG_REMOVE) {
18977            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18978                    + " deleteAllUsers: " + deleteAllUsers + " version="
18979                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18980                    ? "VERSION_CODE_HIGHEST" : versionCode));
18981        }
18982        // Queue up an async operation since the package deletion may take a little while.
18983        mHandler.post(new Runnable() {
18984            public void run() {
18985                mHandler.removeCallbacks(this);
18986                int returnCode;
18987                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18988                boolean doDeletePackage = true;
18989                if (ps != null) {
18990                    final boolean targetIsInstantApp =
18991                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18992                    doDeletePackage = !targetIsInstantApp
18993                            || canViewInstantApps;
18994                }
18995                if (doDeletePackage) {
18996                    if (!deleteAllUsers) {
18997                        returnCode = deletePackageX(internalPackageName, versionCode,
18998                                userId, deleteFlags);
18999                    } else {
19000                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
19001                                internalPackageName, users);
19002                        // If nobody is blocking uninstall, proceed with delete for all users
19003                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
19004                            returnCode = deletePackageX(internalPackageName, versionCode,
19005                                    userId, deleteFlags);
19006                        } else {
19007                            // Otherwise uninstall individually for users with blockUninstalls=false
19008                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
19009                            for (int userId : users) {
19010                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
19011                                    returnCode = deletePackageX(internalPackageName, versionCode,
19012                                            userId, userFlags);
19013                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
19014                                        Slog.w(TAG, "Package delete failed for user " + userId
19015                                                + ", returnCode " + returnCode);
19016                                    }
19017                                }
19018                            }
19019                            // The app has only been marked uninstalled for certain users.
19020                            // We still need to report that delete was blocked
19021                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
19022                        }
19023                    }
19024                } else {
19025                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19026                }
19027                try {
19028                    observer.onPackageDeleted(packageName, returnCode, null);
19029                } catch (RemoteException e) {
19030                    Log.i(TAG, "Observer no longer exists.");
19031                } //end catch
19032            } //end run
19033        });
19034    }
19035
19036    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
19037        if (pkg.staticSharedLibName != null) {
19038            return pkg.manifestPackageName;
19039        }
19040        return pkg.packageName;
19041    }
19042
19043    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
19044        // Handle renamed packages
19045        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
19046        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
19047
19048        // Is this a static library?
19049        SparseArray<SharedLibraryEntry> versionedLib =
19050                mStaticLibsByDeclaringPackage.get(packageName);
19051        if (versionedLib == null || versionedLib.size() <= 0) {
19052            return packageName;
19053        }
19054
19055        // Figure out which lib versions the caller can see
19056        SparseIntArray versionsCallerCanSee = null;
19057        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
19058        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
19059                && callingAppId != Process.ROOT_UID) {
19060            versionsCallerCanSee = new SparseIntArray();
19061            String libName = versionedLib.valueAt(0).info.getName();
19062            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
19063            if (uidPackages != null) {
19064                for (String uidPackage : uidPackages) {
19065                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
19066                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
19067                    if (libIdx >= 0) {
19068                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
19069                        versionsCallerCanSee.append(libVersion, libVersion);
19070                    }
19071                }
19072            }
19073        }
19074
19075        // Caller can see nothing - done
19076        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
19077            return packageName;
19078        }
19079
19080        // Find the version the caller can see and the app version code
19081        SharedLibraryEntry highestVersion = null;
19082        final int versionCount = versionedLib.size();
19083        for (int i = 0; i < versionCount; i++) {
19084            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
19085            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
19086                    libEntry.info.getVersion()) < 0) {
19087                continue;
19088            }
19089            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
19090            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
19091                if (libVersionCode == versionCode) {
19092                    return libEntry.apk;
19093                }
19094            } else if (highestVersion == null) {
19095                highestVersion = libEntry;
19096            } else if (libVersionCode  > highestVersion.info
19097                    .getDeclaringPackage().getVersionCode()) {
19098                highestVersion = libEntry;
19099            }
19100        }
19101
19102        if (highestVersion != null) {
19103            return highestVersion.apk;
19104        }
19105
19106        return packageName;
19107    }
19108
19109    boolean isCallerVerifier(int callingUid) {
19110        final int callingUserId = UserHandle.getUserId(callingUid);
19111        return mRequiredVerifierPackage != null &&
19112                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
19113    }
19114
19115    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
19116        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
19117              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19118            return true;
19119        }
19120        final int callingUserId = UserHandle.getUserId(callingUid);
19121        // If the caller installed the pkgName, then allow it to silently uninstall.
19122        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
19123            return true;
19124        }
19125
19126        // Allow package verifier to silently uninstall.
19127        if (mRequiredVerifierPackage != null &&
19128                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
19129            return true;
19130        }
19131
19132        // Allow package uninstaller to silently uninstall.
19133        if (mRequiredUninstallerPackage != null &&
19134                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
19135            return true;
19136        }
19137
19138        // Allow storage manager to silently uninstall.
19139        if (mStorageManagerPackage != null &&
19140                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
19141            return true;
19142        }
19143
19144        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
19145        // uninstall for device owner provisioning.
19146        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
19147                == PERMISSION_GRANTED) {
19148            return true;
19149        }
19150
19151        return false;
19152    }
19153
19154    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
19155        int[] result = EMPTY_INT_ARRAY;
19156        for (int userId : userIds) {
19157            if (getBlockUninstallForUser(packageName, userId)) {
19158                result = ArrayUtils.appendInt(result, userId);
19159            }
19160        }
19161        return result;
19162    }
19163
19164    @Override
19165    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
19166        final int callingUid = Binder.getCallingUid();
19167        if (getInstantAppPackageName(callingUid) != null
19168                && !isCallerSameApp(packageName, callingUid)) {
19169            return false;
19170        }
19171        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
19172    }
19173
19174    private boolean isPackageDeviceAdmin(String packageName, int userId) {
19175        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
19176                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
19177        try {
19178            if (dpm != null) {
19179                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
19180                        /* callingUserOnly =*/ false);
19181                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
19182                        : deviceOwnerComponentName.getPackageName();
19183                // Does the package contains the device owner?
19184                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
19185                // this check is probably not needed, since DO should be registered as a device
19186                // admin on some user too. (Original bug for this: b/17657954)
19187                if (packageName.equals(deviceOwnerPackageName)) {
19188                    return true;
19189                }
19190                // Does it contain a device admin for any user?
19191                int[] users;
19192                if (userId == UserHandle.USER_ALL) {
19193                    users = sUserManager.getUserIds();
19194                } else {
19195                    users = new int[]{userId};
19196                }
19197                for (int i = 0; i < users.length; ++i) {
19198                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
19199                        return true;
19200                    }
19201                }
19202            }
19203        } catch (RemoteException e) {
19204        }
19205        return false;
19206    }
19207
19208    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
19209        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
19210    }
19211
19212    /**
19213     *  This method is an internal method that could be get invoked either
19214     *  to delete an installed package or to clean up a failed installation.
19215     *  After deleting an installed package, a broadcast is sent to notify any
19216     *  listeners that the package has been removed. For cleaning up a failed
19217     *  installation, the broadcast is not necessary since the package's
19218     *  installation wouldn't have sent the initial broadcast either
19219     *  The key steps in deleting a package are
19220     *  deleting the package information in internal structures like mPackages,
19221     *  deleting the packages base directories through installd
19222     *  updating mSettings to reflect current status
19223     *  persisting settings for later use
19224     *  sending a broadcast if necessary
19225     */
19226    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
19227        final PackageRemovedInfo info = new PackageRemovedInfo(this);
19228        final boolean res;
19229
19230        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
19231                ? UserHandle.USER_ALL : userId;
19232
19233        if (isPackageDeviceAdmin(packageName, removeUser)) {
19234            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
19235            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
19236        }
19237
19238        PackageSetting uninstalledPs = null;
19239        PackageParser.Package pkg = null;
19240
19241        // for the uninstall-updates case and restricted profiles, remember the per-
19242        // user handle installed state
19243        int[] allUsers;
19244        synchronized (mPackages) {
19245            uninstalledPs = mSettings.mPackages.get(packageName);
19246            if (uninstalledPs == null) {
19247                Slog.w(TAG, "Not removing non-existent package " + packageName);
19248                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19249            }
19250
19251            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
19252                    && uninstalledPs.versionCode != versionCode) {
19253                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
19254                        + uninstalledPs.versionCode + " != " + versionCode);
19255                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19256            }
19257
19258            // Static shared libs can be declared by any package, so let us not
19259            // allow removing a package if it provides a lib others depend on.
19260            pkg = mPackages.get(packageName);
19261
19262            allUsers = sUserManager.getUserIds();
19263
19264            if (pkg != null && pkg.staticSharedLibName != null) {
19265                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
19266                        pkg.staticSharedLibVersion);
19267                if (libEntry != null) {
19268                    for (int currUserId : allUsers) {
19269                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
19270                            continue;
19271                        }
19272                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
19273                                libEntry.info, 0, currUserId);
19274                        if (!ArrayUtils.isEmpty(libClientPackages)) {
19275                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
19276                                    + " hosting lib " + libEntry.info.getName() + " version "
19277                                    + libEntry.info.getVersion() + " used by " + libClientPackages
19278                                    + " for user " + currUserId);
19279                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
19280                        }
19281                    }
19282                }
19283            }
19284
19285            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
19286        }
19287
19288        final int freezeUser;
19289        if (isUpdatedSystemApp(uninstalledPs)
19290                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
19291            // We're downgrading a system app, which will apply to all users, so
19292            // freeze them all during the downgrade
19293            freezeUser = UserHandle.USER_ALL;
19294        } else {
19295            freezeUser = removeUser;
19296        }
19297
19298        synchronized (mInstallLock) {
19299            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
19300            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
19301                    deleteFlags, "deletePackageX")) {
19302                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
19303                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
19304            }
19305            synchronized (mPackages) {
19306                if (res) {
19307                    if (pkg != null) {
19308                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
19309                    }
19310                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
19311                    updateInstantAppInstallerLocked(packageName);
19312                }
19313            }
19314        }
19315
19316        if (res) {
19317            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
19318            info.sendPackageRemovedBroadcasts(killApp);
19319            info.sendSystemPackageUpdatedBroadcasts();
19320            info.sendSystemPackageAppearedBroadcasts();
19321        }
19322        // Force a gc here.
19323        Runtime.getRuntime().gc();
19324        // Delete the resources here after sending the broadcast to let
19325        // other processes clean up before deleting resources.
19326        if (info.args != null) {
19327            synchronized (mInstallLock) {
19328                info.args.doPostDeleteLI(true);
19329            }
19330        }
19331
19332        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19333    }
19334
19335    static class PackageRemovedInfo {
19336        final PackageSender packageSender;
19337        String removedPackage;
19338        String installerPackageName;
19339        int uid = -1;
19340        int removedAppId = -1;
19341        int[] origUsers;
19342        int[] removedUsers = null;
19343        int[] broadcastUsers = null;
19344        SparseArray<Integer> installReasons;
19345        boolean isRemovedPackageSystemUpdate = false;
19346        boolean isUpdate;
19347        boolean dataRemoved;
19348        boolean removedForAllUsers;
19349        boolean isStaticSharedLib;
19350        // Clean up resources deleted packages.
19351        InstallArgs args = null;
19352        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
19353        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
19354
19355        PackageRemovedInfo(PackageSender packageSender) {
19356            this.packageSender = packageSender;
19357        }
19358
19359        void sendPackageRemovedBroadcasts(boolean killApp) {
19360            sendPackageRemovedBroadcastInternal(killApp);
19361            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
19362            for (int i = 0; i < childCount; i++) {
19363                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19364                childInfo.sendPackageRemovedBroadcastInternal(killApp);
19365            }
19366        }
19367
19368        void sendSystemPackageUpdatedBroadcasts() {
19369            if (isRemovedPackageSystemUpdate) {
19370                sendSystemPackageUpdatedBroadcastsInternal();
19371                final int childCount = (removedChildPackages != null)
19372                        ? removedChildPackages.size() : 0;
19373                for (int i = 0; i < childCount; i++) {
19374                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19375                    if (childInfo.isRemovedPackageSystemUpdate) {
19376                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
19377                    }
19378                }
19379            }
19380        }
19381
19382        void sendSystemPackageAppearedBroadcasts() {
19383            final int packageCount = (appearedChildPackages != null)
19384                    ? appearedChildPackages.size() : 0;
19385            for (int i = 0; i < packageCount; i++) {
19386                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19387                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19388                    true /*sendBootCompleted*/, false /*startReceiver*/,
19389                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
19390            }
19391        }
19392
19393        private void sendSystemPackageUpdatedBroadcastsInternal() {
19394            Bundle extras = new Bundle(2);
19395            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19396            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19397            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19398                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19399            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19400                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19401            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19402                null, null, 0, removedPackage, null, null);
19403            if (installerPackageName != null) {
19404                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19405                        removedPackage, extras, 0 /*flags*/,
19406                        installerPackageName, null, null);
19407                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19408                        removedPackage, extras, 0 /*flags*/,
19409                        installerPackageName, null, null);
19410            }
19411        }
19412
19413        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19414            // Don't send static shared library removal broadcasts as these
19415            // libs are visible only the the apps that depend on them an one
19416            // cannot remove the library if it has a dependency.
19417            if (isStaticSharedLib) {
19418                return;
19419            }
19420            Bundle extras = new Bundle(2);
19421            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19422            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19423            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19424            if (isUpdate || isRemovedPackageSystemUpdate) {
19425                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19426            }
19427            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19428            if (removedPackage != null) {
19429                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19430                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19431                if (installerPackageName != null) {
19432                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19433                            removedPackage, extras, 0 /*flags*/,
19434                            installerPackageName, null, broadcastUsers);
19435                }
19436                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19437                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19438                        removedPackage, extras,
19439                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19440                        null, null, broadcastUsers);
19441                }
19442            }
19443            if (removedAppId >= 0) {
19444                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19445                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19446                    null, null, broadcastUsers);
19447            }
19448        }
19449
19450        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19451            removedUsers = userIds;
19452            if (removedUsers == null) {
19453                broadcastUsers = null;
19454                return;
19455            }
19456
19457            broadcastUsers = EMPTY_INT_ARRAY;
19458            for (int i = userIds.length - 1; i >= 0; --i) {
19459                final int userId = userIds[i];
19460                if (deletedPackageSetting.getInstantApp(userId)) {
19461                    continue;
19462                }
19463                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19464            }
19465        }
19466    }
19467
19468    /*
19469     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19470     * flag is not set, the data directory is removed as well.
19471     * make sure this flag is set for partially installed apps. If not its meaningless to
19472     * delete a partially installed application.
19473     */
19474    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19475            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19476        String packageName = ps.name;
19477        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19478        // Retrieve object to delete permissions for shared user later on
19479        final PackageParser.Package deletedPkg;
19480        final PackageSetting deletedPs;
19481        // reader
19482        synchronized (mPackages) {
19483            deletedPkg = mPackages.get(packageName);
19484            deletedPs = mSettings.mPackages.get(packageName);
19485            if (outInfo != null) {
19486                outInfo.removedPackage = packageName;
19487                outInfo.installerPackageName = ps.installerPackageName;
19488                outInfo.isStaticSharedLib = deletedPkg != null
19489                        && deletedPkg.staticSharedLibName != null;
19490                outInfo.populateUsers(deletedPs == null ? null
19491                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19492            }
19493        }
19494
19495        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19496
19497        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19498            final PackageParser.Package resolvedPkg;
19499            if (deletedPkg != null) {
19500                resolvedPkg = deletedPkg;
19501            } else {
19502                // We don't have a parsed package when it lives on an ejected
19503                // adopted storage device, so fake something together
19504                resolvedPkg = new PackageParser.Package(ps.name);
19505                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19506            }
19507            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19508                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19509            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19510            if (outInfo != null) {
19511                outInfo.dataRemoved = true;
19512            }
19513            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19514        }
19515
19516        int removedAppId = -1;
19517
19518        // writer
19519        synchronized (mPackages) {
19520            boolean installedStateChanged = false;
19521            if (deletedPs != null) {
19522                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19523                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19524                    clearDefaultBrowserIfNeeded(packageName);
19525                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19526                    removedAppId = mSettings.removePackageLPw(packageName);
19527                    if (outInfo != null) {
19528                        outInfo.removedAppId = removedAppId;
19529                    }
19530                    updatePermissionsLPw(deletedPs.name, null, 0);
19531                    if (deletedPs.sharedUser != null) {
19532                        // Remove permissions associated with package. Since runtime
19533                        // permissions are per user we have to kill the removed package
19534                        // or packages running under the shared user of the removed
19535                        // package if revoking the permissions requested only by the removed
19536                        // package is successful and this causes a change in gids.
19537                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19538                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19539                                    userId);
19540                            if (userIdToKill == UserHandle.USER_ALL
19541                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19542                                // If gids changed for this user, kill all affected packages.
19543                                mHandler.post(new Runnable() {
19544                                    @Override
19545                                    public void run() {
19546                                        // This has to happen with no lock held.
19547                                        killApplication(deletedPs.name, deletedPs.appId,
19548                                                KILL_APP_REASON_GIDS_CHANGED);
19549                                    }
19550                                });
19551                                break;
19552                            }
19553                        }
19554                    }
19555                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19556                }
19557                // make sure to preserve per-user disabled state if this removal was just
19558                // a downgrade of a system app to the factory package
19559                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19560                    if (DEBUG_REMOVE) {
19561                        Slog.d(TAG, "Propagating install state across downgrade");
19562                    }
19563                    for (int userId : allUserHandles) {
19564                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19565                        if (DEBUG_REMOVE) {
19566                            Slog.d(TAG, "    user " + userId + " => " + installed);
19567                        }
19568                        if (installed != ps.getInstalled(userId)) {
19569                            installedStateChanged = true;
19570                        }
19571                        ps.setInstalled(installed, userId);
19572                    }
19573                }
19574            }
19575            // can downgrade to reader
19576            if (writeSettings) {
19577                // Save settings now
19578                mSettings.writeLPr();
19579            }
19580            if (installedStateChanged) {
19581                mSettings.writeKernelMappingLPr(ps);
19582            }
19583        }
19584        if (removedAppId != -1) {
19585            // A user ID was deleted here. Go through all users and remove it
19586            // from KeyStore.
19587            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19588        }
19589    }
19590
19591    static boolean locationIsPrivileged(File path) {
19592        try {
19593            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19594                    .getCanonicalPath();
19595            return path.getCanonicalPath().startsWith(privilegedAppDir);
19596        } catch (IOException e) {
19597            Slog.e(TAG, "Unable to access code path " + path);
19598        }
19599        return false;
19600    }
19601
19602    /*
19603     * Tries to delete system package.
19604     */
19605    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19606            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19607            boolean writeSettings) {
19608        if (deletedPs.parentPackageName != null) {
19609            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19610            return false;
19611        }
19612
19613        final boolean applyUserRestrictions
19614                = (allUserHandles != null) && (outInfo.origUsers != null);
19615        final PackageSetting disabledPs;
19616        // Confirm if the system package has been updated
19617        // An updated system app can be deleted. This will also have to restore
19618        // the system pkg from system partition
19619        // reader
19620        synchronized (mPackages) {
19621            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19622        }
19623
19624        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19625                + " disabledPs=" + disabledPs);
19626
19627        if (disabledPs == null) {
19628            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19629            return false;
19630        } else if (DEBUG_REMOVE) {
19631            Slog.d(TAG, "Deleting system pkg from data partition");
19632        }
19633
19634        if (DEBUG_REMOVE) {
19635            if (applyUserRestrictions) {
19636                Slog.d(TAG, "Remembering install states:");
19637                for (int userId : allUserHandles) {
19638                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19639                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19640                }
19641            }
19642        }
19643
19644        // Delete the updated package
19645        outInfo.isRemovedPackageSystemUpdate = true;
19646        if (outInfo.removedChildPackages != null) {
19647            final int childCount = (deletedPs.childPackageNames != null)
19648                    ? deletedPs.childPackageNames.size() : 0;
19649            for (int i = 0; i < childCount; i++) {
19650                String childPackageName = deletedPs.childPackageNames.get(i);
19651                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19652                        .contains(childPackageName)) {
19653                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19654                            childPackageName);
19655                    if (childInfo != null) {
19656                        childInfo.isRemovedPackageSystemUpdate = true;
19657                    }
19658                }
19659            }
19660        }
19661
19662        if (disabledPs.versionCode < deletedPs.versionCode) {
19663            // Delete data for downgrades
19664            flags &= ~PackageManager.DELETE_KEEP_DATA;
19665        } else {
19666            // Preserve data by setting flag
19667            flags |= PackageManager.DELETE_KEEP_DATA;
19668        }
19669
19670        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19671                outInfo, writeSettings, disabledPs.pkg);
19672        if (!ret) {
19673            return false;
19674        }
19675
19676        // writer
19677        synchronized (mPackages) {
19678            // Reinstate the old system package
19679            enableSystemPackageLPw(disabledPs.pkg);
19680            // Remove any native libraries from the upgraded package.
19681            removeNativeBinariesLI(deletedPs);
19682        }
19683
19684        // Install the system package
19685        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19686        int parseFlags = mDefParseFlags
19687                | PackageParser.PARSE_MUST_BE_APK
19688                | PackageParser.PARSE_IS_SYSTEM
19689                | PackageParser.PARSE_IS_SYSTEM_DIR;
19690        if (locationIsPrivileged(disabledPs.codePath)) {
19691            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19692        }
19693
19694        final PackageParser.Package newPkg;
19695        try {
19696            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19697                0 /* currentTime */, null);
19698        } catch (PackageManagerException e) {
19699            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19700                    + e.getMessage());
19701            return false;
19702        }
19703
19704        try {
19705            // update shared libraries for the newly re-installed system package
19706            updateSharedLibrariesLPr(newPkg, null);
19707        } catch (PackageManagerException e) {
19708            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19709        }
19710
19711        prepareAppDataAfterInstallLIF(newPkg);
19712
19713        // writer
19714        synchronized (mPackages) {
19715            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19716
19717            // Propagate the permissions state as we do not want to drop on the floor
19718            // runtime permissions. The update permissions method below will take
19719            // care of removing obsolete permissions and grant install permissions.
19720            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19721            updatePermissionsLPw(newPkg.packageName, newPkg,
19722                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19723
19724            if (applyUserRestrictions) {
19725                boolean installedStateChanged = false;
19726                if (DEBUG_REMOVE) {
19727                    Slog.d(TAG, "Propagating install state across reinstall");
19728                }
19729                for (int userId : allUserHandles) {
19730                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19731                    if (DEBUG_REMOVE) {
19732                        Slog.d(TAG, "    user " + userId + " => " + installed);
19733                    }
19734                    if (installed != ps.getInstalled(userId)) {
19735                        installedStateChanged = true;
19736                    }
19737                    ps.setInstalled(installed, userId);
19738
19739                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19740                }
19741                // Regardless of writeSettings we need to ensure that this restriction
19742                // state propagation is persisted
19743                mSettings.writeAllUsersPackageRestrictionsLPr();
19744                if (installedStateChanged) {
19745                    mSettings.writeKernelMappingLPr(ps);
19746                }
19747            }
19748            // can downgrade to reader here
19749            if (writeSettings) {
19750                mSettings.writeLPr();
19751            }
19752        }
19753        return true;
19754    }
19755
19756    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19757            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19758            PackageRemovedInfo outInfo, boolean writeSettings,
19759            PackageParser.Package replacingPackage) {
19760        synchronized (mPackages) {
19761            if (outInfo != null) {
19762                outInfo.uid = ps.appId;
19763            }
19764
19765            if (outInfo != null && outInfo.removedChildPackages != null) {
19766                final int childCount = (ps.childPackageNames != null)
19767                        ? ps.childPackageNames.size() : 0;
19768                for (int i = 0; i < childCount; i++) {
19769                    String childPackageName = ps.childPackageNames.get(i);
19770                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19771                    if (childPs == null) {
19772                        return false;
19773                    }
19774                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19775                            childPackageName);
19776                    if (childInfo != null) {
19777                        childInfo.uid = childPs.appId;
19778                    }
19779                }
19780            }
19781        }
19782
19783        // Delete package data from internal structures and also remove data if flag is set
19784        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19785
19786        // Delete the child packages data
19787        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19788        for (int i = 0; i < childCount; i++) {
19789            PackageSetting childPs;
19790            synchronized (mPackages) {
19791                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19792            }
19793            if (childPs != null) {
19794                PackageRemovedInfo childOutInfo = (outInfo != null
19795                        && outInfo.removedChildPackages != null)
19796                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19797                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19798                        && (replacingPackage != null
19799                        && !replacingPackage.hasChildPackage(childPs.name))
19800                        ? flags & ~DELETE_KEEP_DATA : flags;
19801                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19802                        deleteFlags, writeSettings);
19803            }
19804        }
19805
19806        // Delete application code and resources only for parent packages
19807        if (ps.parentPackageName == null) {
19808            if (deleteCodeAndResources && (outInfo != null)) {
19809                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19810                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19811                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19812            }
19813        }
19814
19815        return true;
19816    }
19817
19818    @Override
19819    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19820            int userId) {
19821        mContext.enforceCallingOrSelfPermission(
19822                android.Manifest.permission.DELETE_PACKAGES, null);
19823        synchronized (mPackages) {
19824            // Cannot block uninstall of static shared libs as they are
19825            // considered a part of the using app (emulating static linking).
19826            // Also static libs are installed always on internal storage.
19827            PackageParser.Package pkg = mPackages.get(packageName);
19828            if (pkg != null && pkg.staticSharedLibName != null) {
19829                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19830                        + " providing static shared library: " + pkg.staticSharedLibName);
19831                return false;
19832            }
19833            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19834            mSettings.writePackageRestrictionsLPr(userId);
19835        }
19836        return true;
19837    }
19838
19839    @Override
19840    public boolean getBlockUninstallForUser(String packageName, int userId) {
19841        synchronized (mPackages) {
19842            final PackageSetting ps = mSettings.mPackages.get(packageName);
19843            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19844                return false;
19845            }
19846            return mSettings.getBlockUninstallLPr(userId, packageName);
19847        }
19848    }
19849
19850    @Override
19851    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19852        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19853        synchronized (mPackages) {
19854            PackageSetting ps = mSettings.mPackages.get(packageName);
19855            if (ps == null) {
19856                Log.w(TAG, "Package doesn't exist: " + packageName);
19857                return false;
19858            }
19859            if (systemUserApp) {
19860                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19861            } else {
19862                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19863            }
19864            mSettings.writeLPr();
19865        }
19866        return true;
19867    }
19868
19869    /*
19870     * This method handles package deletion in general
19871     */
19872    private boolean deletePackageLIF(String packageName, UserHandle user,
19873            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19874            PackageRemovedInfo outInfo, boolean writeSettings,
19875            PackageParser.Package replacingPackage) {
19876        if (packageName == null) {
19877            Slog.w(TAG, "Attempt to delete null packageName.");
19878            return false;
19879        }
19880
19881        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19882
19883        PackageSetting ps;
19884        synchronized (mPackages) {
19885            ps = mSettings.mPackages.get(packageName);
19886            if (ps == null) {
19887                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19888                return false;
19889            }
19890
19891            if (ps.parentPackageName != null && (!isSystemApp(ps)
19892                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19893                if (DEBUG_REMOVE) {
19894                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19895                            + ((user == null) ? UserHandle.USER_ALL : user));
19896                }
19897                final int removedUserId = (user != null) ? user.getIdentifier()
19898                        : UserHandle.USER_ALL;
19899                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19900                    return false;
19901                }
19902                markPackageUninstalledForUserLPw(ps, user);
19903                scheduleWritePackageRestrictionsLocked(user);
19904                return true;
19905            }
19906        }
19907
19908        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19909                && user.getIdentifier() != UserHandle.USER_ALL)) {
19910            // The caller is asking that the package only be deleted for a single
19911            // user.  To do this, we just mark its uninstalled state and delete
19912            // its data. If this is a system app, we only allow this to happen if
19913            // they have set the special DELETE_SYSTEM_APP which requests different
19914            // semantics than normal for uninstalling system apps.
19915            markPackageUninstalledForUserLPw(ps, user);
19916
19917            if (!isSystemApp(ps)) {
19918                // Do not uninstall the APK if an app should be cached
19919                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19920                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19921                    // Other user still have this package installed, so all
19922                    // we need to do is clear this user's data and save that
19923                    // it is uninstalled.
19924                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19925                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19926                        return false;
19927                    }
19928                    scheduleWritePackageRestrictionsLocked(user);
19929                    return true;
19930                } else {
19931                    // We need to set it back to 'installed' so the uninstall
19932                    // broadcasts will be sent correctly.
19933                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19934                    ps.setInstalled(true, user.getIdentifier());
19935                    mSettings.writeKernelMappingLPr(ps);
19936                }
19937            } else {
19938                // This is a system app, so we assume that the
19939                // other users still have this package installed, so all
19940                // we need to do is clear this user's data and save that
19941                // it is uninstalled.
19942                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19943                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19944                    return false;
19945                }
19946                scheduleWritePackageRestrictionsLocked(user);
19947                return true;
19948            }
19949        }
19950
19951        // If we are deleting a composite package for all users, keep track
19952        // of result for each child.
19953        if (ps.childPackageNames != null && outInfo != null) {
19954            synchronized (mPackages) {
19955                final int childCount = ps.childPackageNames.size();
19956                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19957                for (int i = 0; i < childCount; i++) {
19958                    String childPackageName = ps.childPackageNames.get(i);
19959                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19960                    childInfo.removedPackage = childPackageName;
19961                    childInfo.installerPackageName = ps.installerPackageName;
19962                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19963                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19964                    if (childPs != null) {
19965                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19966                    }
19967                }
19968            }
19969        }
19970
19971        boolean ret = false;
19972        if (isSystemApp(ps)) {
19973            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19974            // When an updated system application is deleted we delete the existing resources
19975            // as well and fall back to existing code in system partition
19976            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19977        } else {
19978            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19979            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19980                    outInfo, writeSettings, replacingPackage);
19981        }
19982
19983        // Take a note whether we deleted the package for all users
19984        if (outInfo != null) {
19985            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19986            if (outInfo.removedChildPackages != null) {
19987                synchronized (mPackages) {
19988                    final int childCount = outInfo.removedChildPackages.size();
19989                    for (int i = 0; i < childCount; i++) {
19990                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19991                        if (childInfo != null) {
19992                            childInfo.removedForAllUsers = mPackages.get(
19993                                    childInfo.removedPackage) == null;
19994                        }
19995                    }
19996                }
19997            }
19998            // If we uninstalled an update to a system app there may be some
19999            // child packages that appeared as they are declared in the system
20000            // app but were not declared in the update.
20001            if (isSystemApp(ps)) {
20002                synchronized (mPackages) {
20003                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
20004                    final int childCount = (updatedPs.childPackageNames != null)
20005                            ? updatedPs.childPackageNames.size() : 0;
20006                    for (int i = 0; i < childCount; i++) {
20007                        String childPackageName = updatedPs.childPackageNames.get(i);
20008                        if (outInfo.removedChildPackages == null
20009                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
20010                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
20011                            if (childPs == null) {
20012                                continue;
20013                            }
20014                            PackageInstalledInfo installRes = new PackageInstalledInfo();
20015                            installRes.name = childPackageName;
20016                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
20017                            installRes.pkg = mPackages.get(childPackageName);
20018                            installRes.uid = childPs.pkg.applicationInfo.uid;
20019                            if (outInfo.appearedChildPackages == null) {
20020                                outInfo.appearedChildPackages = new ArrayMap<>();
20021                            }
20022                            outInfo.appearedChildPackages.put(childPackageName, installRes);
20023                        }
20024                    }
20025                }
20026            }
20027        }
20028
20029        return ret;
20030    }
20031
20032    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
20033        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
20034                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
20035        for (int nextUserId : userIds) {
20036            if (DEBUG_REMOVE) {
20037                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
20038            }
20039            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
20040                    false /*installed*/,
20041                    true /*stopped*/,
20042                    true /*notLaunched*/,
20043                    false /*hidden*/,
20044                    false /*suspended*/,
20045                    false /*instantApp*/,
20046                    false /*virtualPreload*/,
20047                    null /*lastDisableAppCaller*/,
20048                    null /*enabledComponents*/,
20049                    null /*disabledComponents*/,
20050                    ps.readUserState(nextUserId).domainVerificationStatus,
20051                    0, PackageManager.INSTALL_REASON_UNKNOWN);
20052        }
20053        mSettings.writeKernelMappingLPr(ps);
20054    }
20055
20056    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
20057            PackageRemovedInfo outInfo) {
20058        final PackageParser.Package pkg;
20059        synchronized (mPackages) {
20060            pkg = mPackages.get(ps.name);
20061        }
20062
20063        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
20064                : new int[] {userId};
20065        for (int nextUserId : userIds) {
20066            if (DEBUG_REMOVE) {
20067                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
20068                        + nextUserId);
20069            }
20070
20071            destroyAppDataLIF(pkg, userId,
20072                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20073            destroyAppProfilesLIF(pkg, userId);
20074            clearDefaultBrowserIfNeededForUser(ps.name, userId);
20075            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
20076            schedulePackageCleaning(ps.name, nextUserId, false);
20077            synchronized (mPackages) {
20078                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
20079                    scheduleWritePackageRestrictionsLocked(nextUserId);
20080                }
20081                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
20082            }
20083        }
20084
20085        if (outInfo != null) {
20086            outInfo.removedPackage = ps.name;
20087            outInfo.installerPackageName = ps.installerPackageName;
20088            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
20089            outInfo.removedAppId = ps.appId;
20090            outInfo.removedUsers = userIds;
20091            outInfo.broadcastUsers = userIds;
20092        }
20093
20094        return true;
20095    }
20096
20097    private final class ClearStorageConnection implements ServiceConnection {
20098        IMediaContainerService mContainerService;
20099
20100        @Override
20101        public void onServiceConnected(ComponentName name, IBinder service) {
20102            synchronized (this) {
20103                mContainerService = IMediaContainerService.Stub
20104                        .asInterface(Binder.allowBlocking(service));
20105                notifyAll();
20106            }
20107        }
20108
20109        @Override
20110        public void onServiceDisconnected(ComponentName name) {
20111        }
20112    }
20113
20114    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
20115        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
20116
20117        final boolean mounted;
20118        if (Environment.isExternalStorageEmulated()) {
20119            mounted = true;
20120        } else {
20121            final String status = Environment.getExternalStorageState();
20122
20123            mounted = status.equals(Environment.MEDIA_MOUNTED)
20124                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
20125        }
20126
20127        if (!mounted) {
20128            return;
20129        }
20130
20131        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
20132        int[] users;
20133        if (userId == UserHandle.USER_ALL) {
20134            users = sUserManager.getUserIds();
20135        } else {
20136            users = new int[] { userId };
20137        }
20138        final ClearStorageConnection conn = new ClearStorageConnection();
20139        if (mContext.bindServiceAsUser(
20140                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
20141            try {
20142                for (int curUser : users) {
20143                    long timeout = SystemClock.uptimeMillis() + 5000;
20144                    synchronized (conn) {
20145                        long now;
20146                        while (conn.mContainerService == null &&
20147                                (now = SystemClock.uptimeMillis()) < timeout) {
20148                            try {
20149                                conn.wait(timeout - now);
20150                            } catch (InterruptedException e) {
20151                            }
20152                        }
20153                    }
20154                    if (conn.mContainerService == null) {
20155                        return;
20156                    }
20157
20158                    final UserEnvironment userEnv = new UserEnvironment(curUser);
20159                    clearDirectory(conn.mContainerService,
20160                            userEnv.buildExternalStorageAppCacheDirs(packageName));
20161                    if (allData) {
20162                        clearDirectory(conn.mContainerService,
20163                                userEnv.buildExternalStorageAppDataDirs(packageName));
20164                        clearDirectory(conn.mContainerService,
20165                                userEnv.buildExternalStorageAppMediaDirs(packageName));
20166                    }
20167                }
20168            } finally {
20169                mContext.unbindService(conn);
20170            }
20171        }
20172    }
20173
20174    @Override
20175    public void clearApplicationProfileData(String packageName) {
20176        enforceSystemOrRoot("Only the system can clear all profile data");
20177
20178        final PackageParser.Package pkg;
20179        synchronized (mPackages) {
20180            pkg = mPackages.get(packageName);
20181        }
20182
20183        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
20184            synchronized (mInstallLock) {
20185                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
20186            }
20187        }
20188    }
20189
20190    @Override
20191    public void clearApplicationUserData(final String packageName,
20192            final IPackageDataObserver observer, final int userId) {
20193        mContext.enforceCallingOrSelfPermission(
20194                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
20195
20196        final int callingUid = Binder.getCallingUid();
20197        enforceCrossUserPermission(callingUid, userId,
20198                true /* requireFullPermission */, false /* checkShell */, "clear application data");
20199
20200        final PackageSetting ps = mSettings.getPackageLPr(packageName);
20201        if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
20202            return;
20203        }
20204        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
20205            throw new SecurityException("Cannot clear data for a protected package: "
20206                    + packageName);
20207        }
20208        // Queue up an async operation since the package deletion may take a little while.
20209        mHandler.post(new Runnable() {
20210            public void run() {
20211                mHandler.removeCallbacks(this);
20212                final boolean succeeded;
20213                try (PackageFreezer freezer = freezePackage(packageName,
20214                        "clearApplicationUserData")) {
20215                    synchronized (mInstallLock) {
20216                        succeeded = clearApplicationUserDataLIF(packageName, userId);
20217                    }
20218                    clearExternalStorageDataSync(packageName, userId, true);
20219                    synchronized (mPackages) {
20220                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
20221                                packageName, userId);
20222                    }
20223                }
20224                if (succeeded) {
20225                    // invoke DeviceStorageMonitor's update method to clear any notifications
20226                    DeviceStorageMonitorInternal dsm = LocalServices
20227                            .getService(DeviceStorageMonitorInternal.class);
20228                    if (dsm != null) {
20229                        dsm.checkMemory();
20230                    }
20231                }
20232                if(observer != null) {
20233                    try {
20234                        observer.onRemoveCompleted(packageName, succeeded);
20235                    } catch (RemoteException e) {
20236                        Log.i(TAG, "Observer no longer exists.");
20237                    }
20238                } //end if observer
20239            } //end run
20240        });
20241    }
20242
20243    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
20244        if (packageName == null) {
20245            Slog.w(TAG, "Attempt to delete null packageName.");
20246            return false;
20247        }
20248
20249        // Try finding details about the requested package
20250        PackageParser.Package pkg;
20251        synchronized (mPackages) {
20252            pkg = mPackages.get(packageName);
20253            if (pkg == null) {
20254                final PackageSetting ps = mSettings.mPackages.get(packageName);
20255                if (ps != null) {
20256                    pkg = ps.pkg;
20257                }
20258            }
20259
20260            if (pkg == null) {
20261                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20262                return false;
20263            }
20264
20265            PackageSetting ps = (PackageSetting) pkg.mExtras;
20266            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20267        }
20268
20269        clearAppDataLIF(pkg, userId,
20270                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20271
20272        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20273        removeKeystoreDataIfNeeded(userId, appId);
20274
20275        UserManagerInternal umInternal = getUserManagerInternal();
20276        final int flags;
20277        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
20278            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20279        } else if (umInternal.isUserRunning(userId)) {
20280            flags = StorageManager.FLAG_STORAGE_DE;
20281        } else {
20282            flags = 0;
20283        }
20284        prepareAppDataContentsLIF(pkg, userId, flags);
20285
20286        return true;
20287    }
20288
20289    /**
20290     * Reverts user permission state changes (permissions and flags) in
20291     * all packages for a given user.
20292     *
20293     * @param userId The device user for which to do a reset.
20294     */
20295    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
20296        final int packageCount = mPackages.size();
20297        for (int i = 0; i < packageCount; i++) {
20298            PackageParser.Package pkg = mPackages.valueAt(i);
20299            PackageSetting ps = (PackageSetting) pkg.mExtras;
20300            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20301        }
20302    }
20303
20304    private void resetNetworkPolicies(int userId) {
20305        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
20306    }
20307
20308    /**
20309     * Reverts user permission state changes (permissions and flags).
20310     *
20311     * @param ps The package for which to reset.
20312     * @param userId The device user for which to do a reset.
20313     */
20314    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
20315            final PackageSetting ps, final int userId) {
20316        if (ps.pkg == null) {
20317            return;
20318        }
20319
20320        // These are flags that can change base on user actions.
20321        final int userSettableMask = FLAG_PERMISSION_USER_SET
20322                | FLAG_PERMISSION_USER_FIXED
20323                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
20324                | FLAG_PERMISSION_REVIEW_REQUIRED;
20325
20326        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
20327                | FLAG_PERMISSION_POLICY_FIXED;
20328
20329        boolean writeInstallPermissions = false;
20330        boolean writeRuntimePermissions = false;
20331
20332        final int permissionCount = ps.pkg.requestedPermissions.size();
20333        for (int i = 0; i < permissionCount; i++) {
20334            String permission = ps.pkg.requestedPermissions.get(i);
20335
20336            BasePermission bp = mSettings.mPermissions.get(permission);
20337            if (bp == null) {
20338                continue;
20339            }
20340
20341            // If shared user we just reset the state to which only this app contributed.
20342            if (ps.sharedUser != null) {
20343                boolean used = false;
20344                final int packageCount = ps.sharedUser.packages.size();
20345                for (int j = 0; j < packageCount; j++) {
20346                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
20347                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
20348                            && pkg.pkg.requestedPermissions.contains(permission)) {
20349                        used = true;
20350                        break;
20351                    }
20352                }
20353                if (used) {
20354                    continue;
20355                }
20356            }
20357
20358            PermissionsState permissionsState = ps.getPermissionsState();
20359
20360            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
20361
20362            // Always clear the user settable flags.
20363            final boolean hasInstallState = permissionsState.getInstallPermissionState(
20364                    bp.name) != null;
20365            // If permission review is enabled and this is a legacy app, mark the
20366            // permission as requiring a review as this is the initial state.
20367            int flags = 0;
20368            if (mPermissionReviewRequired
20369                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
20370                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
20371            }
20372            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
20373                if (hasInstallState) {
20374                    writeInstallPermissions = true;
20375                } else {
20376                    writeRuntimePermissions = true;
20377                }
20378            }
20379
20380            // Below is only runtime permission handling.
20381            if (!bp.isRuntime()) {
20382                continue;
20383            }
20384
20385            // Never clobber system or policy.
20386            if ((oldFlags & policyOrSystemFlags) != 0) {
20387                continue;
20388            }
20389
20390            // If this permission was granted by default, make sure it is.
20391            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20392                if (permissionsState.grantRuntimePermission(bp, userId)
20393                        != PERMISSION_OPERATION_FAILURE) {
20394                    writeRuntimePermissions = true;
20395                }
20396            // If permission review is enabled the permissions for a legacy apps
20397            // are represented as constantly granted runtime ones, so don't revoke.
20398            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20399                // Otherwise, reset the permission.
20400                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20401                switch (revokeResult) {
20402                    case PERMISSION_OPERATION_SUCCESS:
20403                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20404                        writeRuntimePermissions = true;
20405                        final int appId = ps.appId;
20406                        mHandler.post(new Runnable() {
20407                            @Override
20408                            public void run() {
20409                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20410                            }
20411                        });
20412                    } break;
20413                }
20414            }
20415        }
20416
20417        // Synchronously write as we are taking permissions away.
20418        if (writeRuntimePermissions) {
20419            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20420        }
20421
20422        // Synchronously write as we are taking permissions away.
20423        if (writeInstallPermissions) {
20424            mSettings.writeLPr();
20425        }
20426    }
20427
20428    /**
20429     * Remove entries from the keystore daemon. Will only remove it if the
20430     * {@code appId} is valid.
20431     */
20432    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20433        if (appId < 0) {
20434            return;
20435        }
20436
20437        final KeyStore keyStore = KeyStore.getInstance();
20438        if (keyStore != null) {
20439            if (userId == UserHandle.USER_ALL) {
20440                for (final int individual : sUserManager.getUserIds()) {
20441                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20442                }
20443            } else {
20444                keyStore.clearUid(UserHandle.getUid(userId, appId));
20445            }
20446        } else {
20447            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20448        }
20449    }
20450
20451    @Override
20452    public void deleteApplicationCacheFiles(final String packageName,
20453            final IPackageDataObserver observer) {
20454        final int userId = UserHandle.getCallingUserId();
20455        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20456    }
20457
20458    @Override
20459    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20460            final IPackageDataObserver observer) {
20461        final int callingUid = Binder.getCallingUid();
20462        mContext.enforceCallingOrSelfPermission(
20463                android.Manifest.permission.DELETE_CACHE_FILES, null);
20464        enforceCrossUserPermission(callingUid, userId,
20465                /* requireFullPermission= */ true, /* checkShell= */ false,
20466                "delete application cache files");
20467        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20468                android.Manifest.permission.ACCESS_INSTANT_APPS);
20469
20470        final PackageParser.Package pkg;
20471        synchronized (mPackages) {
20472            pkg = mPackages.get(packageName);
20473        }
20474
20475        // Queue up an async operation since the package deletion may take a little while.
20476        mHandler.post(new Runnable() {
20477            public void run() {
20478                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20479                boolean doClearData = true;
20480                if (ps != null) {
20481                    final boolean targetIsInstantApp =
20482                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20483                    doClearData = !targetIsInstantApp
20484                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20485                }
20486                if (doClearData) {
20487                    synchronized (mInstallLock) {
20488                        final int flags = StorageManager.FLAG_STORAGE_DE
20489                                | StorageManager.FLAG_STORAGE_CE;
20490                        // We're only clearing cache files, so we don't care if the
20491                        // app is unfrozen and still able to run
20492                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20493                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20494                    }
20495                    clearExternalStorageDataSync(packageName, userId, false);
20496                }
20497                if (observer != null) {
20498                    try {
20499                        observer.onRemoveCompleted(packageName, true);
20500                    } catch (RemoteException e) {
20501                        Log.i(TAG, "Observer no longer exists.");
20502                    }
20503                }
20504            }
20505        });
20506    }
20507
20508    @Override
20509    public void getPackageSizeInfo(final String packageName, int userHandle,
20510            final IPackageStatsObserver observer) {
20511        throw new UnsupportedOperationException(
20512                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20513    }
20514
20515    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20516        final PackageSetting ps;
20517        synchronized (mPackages) {
20518            ps = mSettings.mPackages.get(packageName);
20519            if (ps == null) {
20520                Slog.w(TAG, "Failed to find settings for " + packageName);
20521                return false;
20522            }
20523        }
20524
20525        final String[] packageNames = { packageName };
20526        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20527        final String[] codePaths = { ps.codePathString };
20528
20529        try {
20530            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20531                    ps.appId, ceDataInodes, codePaths, stats);
20532
20533            // For now, ignore code size of packages on system partition
20534            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20535                stats.codeSize = 0;
20536            }
20537
20538            // External clients expect these to be tracked separately
20539            stats.dataSize -= stats.cacheSize;
20540
20541        } catch (InstallerException e) {
20542            Slog.w(TAG, String.valueOf(e));
20543            return false;
20544        }
20545
20546        return true;
20547    }
20548
20549    private int getUidTargetSdkVersionLockedLPr(int uid) {
20550        Object obj = mSettings.getUserIdLPr(uid);
20551        if (obj instanceof SharedUserSetting) {
20552            final SharedUserSetting sus = (SharedUserSetting) obj;
20553            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20554            final Iterator<PackageSetting> it = sus.packages.iterator();
20555            while (it.hasNext()) {
20556                final PackageSetting ps = it.next();
20557                if (ps.pkg != null) {
20558                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20559                    if (v < vers) vers = v;
20560                }
20561            }
20562            return vers;
20563        } else if (obj instanceof PackageSetting) {
20564            final PackageSetting ps = (PackageSetting) obj;
20565            if (ps.pkg != null) {
20566                return ps.pkg.applicationInfo.targetSdkVersion;
20567            }
20568        }
20569        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20570    }
20571
20572    @Override
20573    public void addPreferredActivity(IntentFilter filter, int match,
20574            ComponentName[] set, ComponentName activity, int userId) {
20575        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20576                "Adding preferred");
20577    }
20578
20579    private void addPreferredActivityInternal(IntentFilter filter, int match,
20580            ComponentName[] set, ComponentName activity, boolean always, int userId,
20581            String opname) {
20582        // writer
20583        int callingUid = Binder.getCallingUid();
20584        enforceCrossUserPermission(callingUid, userId,
20585                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20586        if (filter.countActions() == 0) {
20587            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20588            return;
20589        }
20590        synchronized (mPackages) {
20591            if (mContext.checkCallingOrSelfPermission(
20592                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20593                    != PackageManager.PERMISSION_GRANTED) {
20594                if (getUidTargetSdkVersionLockedLPr(callingUid)
20595                        < Build.VERSION_CODES.FROYO) {
20596                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20597                            + callingUid);
20598                    return;
20599                }
20600                mContext.enforceCallingOrSelfPermission(
20601                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20602            }
20603
20604            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20605            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20606                    + userId + ":");
20607            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20608            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20609            scheduleWritePackageRestrictionsLocked(userId);
20610            postPreferredActivityChangedBroadcast(userId);
20611        }
20612    }
20613
20614    private void postPreferredActivityChangedBroadcast(int userId) {
20615        mHandler.post(() -> {
20616            final IActivityManager am = ActivityManager.getService();
20617            if (am == null) {
20618                return;
20619            }
20620
20621            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20622            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20623            try {
20624                am.broadcastIntent(null, intent, null, null,
20625                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20626                        null, false, false, userId);
20627            } catch (RemoteException e) {
20628            }
20629        });
20630    }
20631
20632    @Override
20633    public void replacePreferredActivity(IntentFilter filter, int match,
20634            ComponentName[] set, ComponentName activity, int userId) {
20635        if (filter.countActions() != 1) {
20636            throw new IllegalArgumentException(
20637                    "replacePreferredActivity expects filter to have only 1 action.");
20638        }
20639        if (filter.countDataAuthorities() != 0
20640                || filter.countDataPaths() != 0
20641                || filter.countDataSchemes() > 1
20642                || filter.countDataTypes() != 0) {
20643            throw new IllegalArgumentException(
20644                    "replacePreferredActivity expects filter to have no data authorities, " +
20645                    "paths, or types; and at most one scheme.");
20646        }
20647
20648        final int callingUid = Binder.getCallingUid();
20649        enforceCrossUserPermission(callingUid, userId,
20650                true /* requireFullPermission */, false /* checkShell */,
20651                "replace preferred activity");
20652        synchronized (mPackages) {
20653            if (mContext.checkCallingOrSelfPermission(
20654                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20655                    != PackageManager.PERMISSION_GRANTED) {
20656                if (getUidTargetSdkVersionLockedLPr(callingUid)
20657                        < Build.VERSION_CODES.FROYO) {
20658                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20659                            + Binder.getCallingUid());
20660                    return;
20661                }
20662                mContext.enforceCallingOrSelfPermission(
20663                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20664            }
20665
20666            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20667            if (pir != null) {
20668                // Get all of the existing entries that exactly match this filter.
20669                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20670                if (existing != null && existing.size() == 1) {
20671                    PreferredActivity cur = existing.get(0);
20672                    if (DEBUG_PREFERRED) {
20673                        Slog.i(TAG, "Checking replace of preferred:");
20674                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20675                        if (!cur.mPref.mAlways) {
20676                            Slog.i(TAG, "  -- CUR; not mAlways!");
20677                        } else {
20678                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20679                            Slog.i(TAG, "  -- CUR: mSet="
20680                                    + Arrays.toString(cur.mPref.mSetComponents));
20681                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20682                            Slog.i(TAG, "  -- NEW: mMatch="
20683                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20684                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20685                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20686                        }
20687                    }
20688                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20689                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20690                            && cur.mPref.sameSet(set)) {
20691                        // Setting the preferred activity to what it happens to be already
20692                        if (DEBUG_PREFERRED) {
20693                            Slog.i(TAG, "Replacing with same preferred activity "
20694                                    + cur.mPref.mShortComponent + " for user "
20695                                    + userId + ":");
20696                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20697                        }
20698                        return;
20699                    }
20700                }
20701
20702                if (existing != null) {
20703                    if (DEBUG_PREFERRED) {
20704                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20705                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20706                    }
20707                    for (int i = 0; i < existing.size(); i++) {
20708                        PreferredActivity pa = existing.get(i);
20709                        if (DEBUG_PREFERRED) {
20710                            Slog.i(TAG, "Removing existing preferred activity "
20711                                    + pa.mPref.mComponent + ":");
20712                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20713                        }
20714                        pir.removeFilter(pa);
20715                    }
20716                }
20717            }
20718            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20719                    "Replacing preferred");
20720        }
20721    }
20722
20723    @Override
20724    public void clearPackagePreferredActivities(String packageName) {
20725        final int callingUid = Binder.getCallingUid();
20726        if (getInstantAppPackageName(callingUid) != null) {
20727            return;
20728        }
20729        // writer
20730        synchronized (mPackages) {
20731            PackageParser.Package pkg = mPackages.get(packageName);
20732            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20733                if (mContext.checkCallingOrSelfPermission(
20734                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20735                        != PackageManager.PERMISSION_GRANTED) {
20736                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20737                            < Build.VERSION_CODES.FROYO) {
20738                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20739                                + callingUid);
20740                        return;
20741                    }
20742                    mContext.enforceCallingOrSelfPermission(
20743                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20744                }
20745            }
20746            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20747            if (ps != null
20748                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20749                return;
20750            }
20751            int user = UserHandle.getCallingUserId();
20752            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20753                scheduleWritePackageRestrictionsLocked(user);
20754            }
20755        }
20756    }
20757
20758    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20759    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20760        ArrayList<PreferredActivity> removed = null;
20761        boolean changed = false;
20762        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20763            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20764            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20765            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20766                continue;
20767            }
20768            Iterator<PreferredActivity> it = pir.filterIterator();
20769            while (it.hasNext()) {
20770                PreferredActivity pa = it.next();
20771                // Mark entry for removal only if it matches the package name
20772                // and the entry is of type "always".
20773                if (packageName == null ||
20774                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20775                                && pa.mPref.mAlways)) {
20776                    if (removed == null) {
20777                        removed = new ArrayList<PreferredActivity>();
20778                    }
20779                    removed.add(pa);
20780                }
20781            }
20782            if (removed != null) {
20783                for (int j=0; j<removed.size(); j++) {
20784                    PreferredActivity pa = removed.get(j);
20785                    pir.removeFilter(pa);
20786                }
20787                changed = true;
20788            }
20789        }
20790        if (changed) {
20791            postPreferredActivityChangedBroadcast(userId);
20792        }
20793        return changed;
20794    }
20795
20796    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20797    private void clearIntentFilterVerificationsLPw(int userId) {
20798        final int packageCount = mPackages.size();
20799        for (int i = 0; i < packageCount; i++) {
20800            PackageParser.Package pkg = mPackages.valueAt(i);
20801            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20802        }
20803    }
20804
20805    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20806    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20807        if (userId == UserHandle.USER_ALL) {
20808            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20809                    sUserManager.getUserIds())) {
20810                for (int oneUserId : sUserManager.getUserIds()) {
20811                    scheduleWritePackageRestrictionsLocked(oneUserId);
20812                }
20813            }
20814        } else {
20815            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20816                scheduleWritePackageRestrictionsLocked(userId);
20817            }
20818        }
20819    }
20820
20821    /** Clears state for all users, and touches intent filter verification policy */
20822    void clearDefaultBrowserIfNeeded(String packageName) {
20823        for (int oneUserId : sUserManager.getUserIds()) {
20824            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20825        }
20826    }
20827
20828    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20829        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20830        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20831            if (packageName.equals(defaultBrowserPackageName)) {
20832                setDefaultBrowserPackageName(null, userId);
20833            }
20834        }
20835    }
20836
20837    @Override
20838    public void resetApplicationPreferences(int userId) {
20839        mContext.enforceCallingOrSelfPermission(
20840                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20841        final long identity = Binder.clearCallingIdentity();
20842        // writer
20843        try {
20844            synchronized (mPackages) {
20845                clearPackagePreferredActivitiesLPw(null, userId);
20846                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20847                // TODO: We have to reset the default SMS and Phone. This requires
20848                // significant refactoring to keep all default apps in the package
20849                // manager (cleaner but more work) or have the services provide
20850                // callbacks to the package manager to request a default app reset.
20851                applyFactoryDefaultBrowserLPw(userId);
20852                clearIntentFilterVerificationsLPw(userId);
20853                primeDomainVerificationsLPw(userId);
20854                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20855                scheduleWritePackageRestrictionsLocked(userId);
20856            }
20857            resetNetworkPolicies(userId);
20858        } finally {
20859            Binder.restoreCallingIdentity(identity);
20860        }
20861    }
20862
20863    @Override
20864    public int getPreferredActivities(List<IntentFilter> outFilters,
20865            List<ComponentName> outActivities, String packageName) {
20866        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20867            return 0;
20868        }
20869        int num = 0;
20870        final int userId = UserHandle.getCallingUserId();
20871        // reader
20872        synchronized (mPackages) {
20873            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20874            if (pir != null) {
20875                final Iterator<PreferredActivity> it = pir.filterIterator();
20876                while (it.hasNext()) {
20877                    final PreferredActivity pa = it.next();
20878                    if (packageName == null
20879                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20880                                    && pa.mPref.mAlways)) {
20881                        if (outFilters != null) {
20882                            outFilters.add(new IntentFilter(pa));
20883                        }
20884                        if (outActivities != null) {
20885                            outActivities.add(pa.mPref.mComponent);
20886                        }
20887                    }
20888                }
20889            }
20890        }
20891
20892        return num;
20893    }
20894
20895    @Override
20896    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20897            int userId) {
20898        int callingUid = Binder.getCallingUid();
20899        if (callingUid != Process.SYSTEM_UID) {
20900            throw new SecurityException(
20901                    "addPersistentPreferredActivity can only be run by the system");
20902        }
20903        if (filter.countActions() == 0) {
20904            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20905            return;
20906        }
20907        synchronized (mPackages) {
20908            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20909                    ":");
20910            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20911            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20912                    new PersistentPreferredActivity(filter, activity));
20913            scheduleWritePackageRestrictionsLocked(userId);
20914            postPreferredActivityChangedBroadcast(userId);
20915        }
20916    }
20917
20918    @Override
20919    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20920        int callingUid = Binder.getCallingUid();
20921        if (callingUid != Process.SYSTEM_UID) {
20922            throw new SecurityException(
20923                    "clearPackagePersistentPreferredActivities can only be run by the system");
20924        }
20925        ArrayList<PersistentPreferredActivity> removed = null;
20926        boolean changed = false;
20927        synchronized (mPackages) {
20928            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20929                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20930                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20931                        .valueAt(i);
20932                if (userId != thisUserId) {
20933                    continue;
20934                }
20935                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20936                while (it.hasNext()) {
20937                    PersistentPreferredActivity ppa = it.next();
20938                    // Mark entry for removal only if it matches the package name.
20939                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20940                        if (removed == null) {
20941                            removed = new ArrayList<PersistentPreferredActivity>();
20942                        }
20943                        removed.add(ppa);
20944                    }
20945                }
20946                if (removed != null) {
20947                    for (int j=0; j<removed.size(); j++) {
20948                        PersistentPreferredActivity ppa = removed.get(j);
20949                        ppir.removeFilter(ppa);
20950                    }
20951                    changed = true;
20952                }
20953            }
20954
20955            if (changed) {
20956                scheduleWritePackageRestrictionsLocked(userId);
20957                postPreferredActivityChangedBroadcast(userId);
20958            }
20959        }
20960    }
20961
20962    /**
20963     * Common machinery for picking apart a restored XML blob and passing
20964     * it to a caller-supplied functor to be applied to the running system.
20965     */
20966    private void restoreFromXml(XmlPullParser parser, int userId,
20967            String expectedStartTag, BlobXmlRestorer functor)
20968            throws IOException, XmlPullParserException {
20969        int type;
20970        while ((type = parser.next()) != XmlPullParser.START_TAG
20971                && type != XmlPullParser.END_DOCUMENT) {
20972        }
20973        if (type != XmlPullParser.START_TAG) {
20974            // oops didn't find a start tag?!
20975            if (DEBUG_BACKUP) {
20976                Slog.e(TAG, "Didn't find start tag during restore");
20977            }
20978            return;
20979        }
20980Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20981        // this is supposed to be TAG_PREFERRED_BACKUP
20982        if (!expectedStartTag.equals(parser.getName())) {
20983            if (DEBUG_BACKUP) {
20984                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20985            }
20986            return;
20987        }
20988
20989        // skip interfering stuff, then we're aligned with the backing implementation
20990        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20991Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20992        functor.apply(parser, userId);
20993    }
20994
20995    private interface BlobXmlRestorer {
20996        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20997    }
20998
20999    /**
21000     * Non-Binder method, support for the backup/restore mechanism: write the
21001     * full set of preferred activities in its canonical XML format.  Returns the
21002     * XML output as a byte array, or null if there is none.
21003     */
21004    @Override
21005    public byte[] getPreferredActivityBackup(int userId) {
21006        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21007            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
21008        }
21009
21010        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21011        try {
21012            final XmlSerializer serializer = new FastXmlSerializer();
21013            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21014            serializer.startDocument(null, true);
21015            serializer.startTag(null, TAG_PREFERRED_BACKUP);
21016
21017            synchronized (mPackages) {
21018                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
21019            }
21020
21021            serializer.endTag(null, TAG_PREFERRED_BACKUP);
21022            serializer.endDocument();
21023            serializer.flush();
21024        } catch (Exception e) {
21025            if (DEBUG_BACKUP) {
21026                Slog.e(TAG, "Unable to write preferred activities for backup", e);
21027            }
21028            return null;
21029        }
21030
21031        return dataStream.toByteArray();
21032    }
21033
21034    @Override
21035    public void restorePreferredActivities(byte[] backup, int userId) {
21036        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21037            throw new SecurityException("Only the system may call restorePreferredActivities()");
21038        }
21039
21040        try {
21041            final XmlPullParser parser = Xml.newPullParser();
21042            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21043            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
21044                    new BlobXmlRestorer() {
21045                        @Override
21046                        public void apply(XmlPullParser parser, int userId)
21047                                throws XmlPullParserException, IOException {
21048                            synchronized (mPackages) {
21049                                mSettings.readPreferredActivitiesLPw(parser, userId);
21050                            }
21051                        }
21052                    } );
21053        } catch (Exception e) {
21054            if (DEBUG_BACKUP) {
21055                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21056            }
21057        }
21058    }
21059
21060    /**
21061     * Non-Binder method, support for the backup/restore mechanism: write the
21062     * default browser (etc) settings in its canonical XML format.  Returns the default
21063     * browser XML representation as a byte array, or null if there is none.
21064     */
21065    @Override
21066    public byte[] getDefaultAppsBackup(int userId) {
21067        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21068            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
21069        }
21070
21071        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21072        try {
21073            final XmlSerializer serializer = new FastXmlSerializer();
21074            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21075            serializer.startDocument(null, true);
21076            serializer.startTag(null, TAG_DEFAULT_APPS);
21077
21078            synchronized (mPackages) {
21079                mSettings.writeDefaultAppsLPr(serializer, userId);
21080            }
21081
21082            serializer.endTag(null, TAG_DEFAULT_APPS);
21083            serializer.endDocument();
21084            serializer.flush();
21085        } catch (Exception e) {
21086            if (DEBUG_BACKUP) {
21087                Slog.e(TAG, "Unable to write default apps for backup", e);
21088            }
21089            return null;
21090        }
21091
21092        return dataStream.toByteArray();
21093    }
21094
21095    @Override
21096    public void restoreDefaultApps(byte[] backup, int userId) {
21097        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21098            throw new SecurityException("Only the system may call restoreDefaultApps()");
21099        }
21100
21101        try {
21102            final XmlPullParser parser = Xml.newPullParser();
21103            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21104            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
21105                    new BlobXmlRestorer() {
21106                        @Override
21107                        public void apply(XmlPullParser parser, int userId)
21108                                throws XmlPullParserException, IOException {
21109                            synchronized (mPackages) {
21110                                mSettings.readDefaultAppsLPw(parser, userId);
21111                            }
21112                        }
21113                    } );
21114        } catch (Exception e) {
21115            if (DEBUG_BACKUP) {
21116                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
21117            }
21118        }
21119    }
21120
21121    @Override
21122    public byte[] getIntentFilterVerificationBackup(int userId) {
21123        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21124            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
21125        }
21126
21127        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21128        try {
21129            final XmlSerializer serializer = new FastXmlSerializer();
21130            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21131            serializer.startDocument(null, true);
21132            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
21133
21134            synchronized (mPackages) {
21135                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
21136            }
21137
21138            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
21139            serializer.endDocument();
21140            serializer.flush();
21141        } catch (Exception e) {
21142            if (DEBUG_BACKUP) {
21143                Slog.e(TAG, "Unable to write default apps for backup", e);
21144            }
21145            return null;
21146        }
21147
21148        return dataStream.toByteArray();
21149    }
21150
21151    @Override
21152    public void restoreIntentFilterVerification(byte[] backup, int userId) {
21153        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21154            throw new SecurityException("Only the system may call restorePreferredActivities()");
21155        }
21156
21157        try {
21158            final XmlPullParser parser = Xml.newPullParser();
21159            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21160            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
21161                    new BlobXmlRestorer() {
21162                        @Override
21163                        public void apply(XmlPullParser parser, int userId)
21164                                throws XmlPullParserException, IOException {
21165                            synchronized (mPackages) {
21166                                mSettings.readAllDomainVerificationsLPr(parser, userId);
21167                                mSettings.writeLPr();
21168                            }
21169                        }
21170                    } );
21171        } catch (Exception e) {
21172            if (DEBUG_BACKUP) {
21173                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21174            }
21175        }
21176    }
21177
21178    @Override
21179    public byte[] getPermissionGrantBackup(int userId) {
21180        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21181            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
21182        }
21183
21184        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21185        try {
21186            final XmlSerializer serializer = new FastXmlSerializer();
21187            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21188            serializer.startDocument(null, true);
21189            serializer.startTag(null, TAG_PERMISSION_BACKUP);
21190
21191            synchronized (mPackages) {
21192                serializeRuntimePermissionGrantsLPr(serializer, userId);
21193            }
21194
21195            serializer.endTag(null, TAG_PERMISSION_BACKUP);
21196            serializer.endDocument();
21197            serializer.flush();
21198        } catch (Exception e) {
21199            if (DEBUG_BACKUP) {
21200                Slog.e(TAG, "Unable to write default apps for backup", e);
21201            }
21202            return null;
21203        }
21204
21205        return dataStream.toByteArray();
21206    }
21207
21208    @Override
21209    public void restorePermissionGrants(byte[] backup, int userId) {
21210        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21211            throw new SecurityException("Only the system may call restorePermissionGrants()");
21212        }
21213
21214        try {
21215            final XmlPullParser parser = Xml.newPullParser();
21216            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21217            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
21218                    new BlobXmlRestorer() {
21219                        @Override
21220                        public void apply(XmlPullParser parser, int userId)
21221                                throws XmlPullParserException, IOException {
21222                            synchronized (mPackages) {
21223                                processRestoredPermissionGrantsLPr(parser, userId);
21224                            }
21225                        }
21226                    } );
21227        } catch (Exception e) {
21228            if (DEBUG_BACKUP) {
21229                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21230            }
21231        }
21232    }
21233
21234    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
21235            throws IOException {
21236        serializer.startTag(null, TAG_ALL_GRANTS);
21237
21238        final int N = mSettings.mPackages.size();
21239        for (int i = 0; i < N; i++) {
21240            final PackageSetting ps = mSettings.mPackages.valueAt(i);
21241            boolean pkgGrantsKnown = false;
21242
21243            PermissionsState packagePerms = ps.getPermissionsState();
21244
21245            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
21246                final int grantFlags = state.getFlags();
21247                // only look at grants that are not system/policy fixed
21248                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
21249                    final boolean isGranted = state.isGranted();
21250                    // And only back up the user-twiddled state bits
21251                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
21252                        final String packageName = mSettings.mPackages.keyAt(i);
21253                        if (!pkgGrantsKnown) {
21254                            serializer.startTag(null, TAG_GRANT);
21255                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
21256                            pkgGrantsKnown = true;
21257                        }
21258
21259                        final boolean userSet =
21260                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
21261                        final boolean userFixed =
21262                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
21263                        final boolean revoke =
21264                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
21265
21266                        serializer.startTag(null, TAG_PERMISSION);
21267                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
21268                        if (isGranted) {
21269                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
21270                        }
21271                        if (userSet) {
21272                            serializer.attribute(null, ATTR_USER_SET, "true");
21273                        }
21274                        if (userFixed) {
21275                            serializer.attribute(null, ATTR_USER_FIXED, "true");
21276                        }
21277                        if (revoke) {
21278                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
21279                        }
21280                        serializer.endTag(null, TAG_PERMISSION);
21281                    }
21282                }
21283            }
21284
21285            if (pkgGrantsKnown) {
21286                serializer.endTag(null, TAG_GRANT);
21287            }
21288        }
21289
21290        serializer.endTag(null, TAG_ALL_GRANTS);
21291    }
21292
21293    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
21294            throws XmlPullParserException, IOException {
21295        String pkgName = null;
21296        int outerDepth = parser.getDepth();
21297        int type;
21298        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
21299                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
21300            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
21301                continue;
21302            }
21303
21304            final String tagName = parser.getName();
21305            if (tagName.equals(TAG_GRANT)) {
21306                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
21307                if (DEBUG_BACKUP) {
21308                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
21309                }
21310            } else if (tagName.equals(TAG_PERMISSION)) {
21311
21312                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
21313                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
21314
21315                int newFlagSet = 0;
21316                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
21317                    newFlagSet |= FLAG_PERMISSION_USER_SET;
21318                }
21319                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
21320                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
21321                }
21322                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
21323                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
21324                }
21325                if (DEBUG_BACKUP) {
21326                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
21327                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
21328                }
21329                final PackageSetting ps = mSettings.mPackages.get(pkgName);
21330                if (ps != null) {
21331                    // Already installed so we apply the grant immediately
21332                    if (DEBUG_BACKUP) {
21333                        Slog.v(TAG, "        + already installed; applying");
21334                    }
21335                    PermissionsState perms = ps.getPermissionsState();
21336                    BasePermission bp = mSettings.mPermissions.get(permName);
21337                    if (bp != null) {
21338                        if (isGranted) {
21339                            perms.grantRuntimePermission(bp, userId);
21340                        }
21341                        if (newFlagSet != 0) {
21342                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
21343                        }
21344                    }
21345                } else {
21346                    // Need to wait for post-restore install to apply the grant
21347                    if (DEBUG_BACKUP) {
21348                        Slog.v(TAG, "        - not yet installed; saving for later");
21349                    }
21350                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
21351                            isGranted, newFlagSet, userId);
21352                }
21353            } else {
21354                PackageManagerService.reportSettingsProblem(Log.WARN,
21355                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
21356                XmlUtils.skipCurrentTag(parser);
21357            }
21358        }
21359
21360        scheduleWriteSettingsLocked();
21361        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
21362    }
21363
21364    @Override
21365    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
21366            int sourceUserId, int targetUserId, int flags) {
21367        mContext.enforceCallingOrSelfPermission(
21368                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21369        int callingUid = Binder.getCallingUid();
21370        enforceOwnerRights(ownerPackage, callingUid);
21371        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21372        if (intentFilter.countActions() == 0) {
21373            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
21374            return;
21375        }
21376        synchronized (mPackages) {
21377            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
21378                    ownerPackage, targetUserId, flags);
21379            CrossProfileIntentResolver resolver =
21380                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21381            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
21382            // We have all those whose filter is equal. Now checking if the rest is equal as well.
21383            if (existing != null) {
21384                int size = existing.size();
21385                for (int i = 0; i < size; i++) {
21386                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
21387                        return;
21388                    }
21389                }
21390            }
21391            resolver.addFilter(newFilter);
21392            scheduleWritePackageRestrictionsLocked(sourceUserId);
21393        }
21394    }
21395
21396    @Override
21397    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21398        mContext.enforceCallingOrSelfPermission(
21399                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21400        final int callingUid = Binder.getCallingUid();
21401        enforceOwnerRights(ownerPackage, callingUid);
21402        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21403        synchronized (mPackages) {
21404            CrossProfileIntentResolver resolver =
21405                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21406            ArraySet<CrossProfileIntentFilter> set =
21407                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21408            for (CrossProfileIntentFilter filter : set) {
21409                if (filter.getOwnerPackage().equals(ownerPackage)) {
21410                    resolver.removeFilter(filter);
21411                }
21412            }
21413            scheduleWritePackageRestrictionsLocked(sourceUserId);
21414        }
21415    }
21416
21417    // Enforcing that callingUid is owning pkg on userId
21418    private void enforceOwnerRights(String pkg, int callingUid) {
21419        // The system owns everything.
21420        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21421            return;
21422        }
21423        final int callingUserId = UserHandle.getUserId(callingUid);
21424        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21425        if (pi == null) {
21426            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21427                    + callingUserId);
21428        }
21429        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21430            throw new SecurityException("Calling uid " + callingUid
21431                    + " does not own package " + pkg);
21432        }
21433    }
21434
21435    @Override
21436    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21437        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21438            return null;
21439        }
21440        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21441    }
21442
21443    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21444        UserManagerService ums = UserManagerService.getInstance();
21445        if (ums != null) {
21446            final UserInfo parent = ums.getProfileParent(userId);
21447            final int launcherUid = (parent != null) ? parent.id : userId;
21448            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21449            if (launcherComponent != null) {
21450                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21451                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21452                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21453                        .setPackage(launcherComponent.getPackageName());
21454                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21455            }
21456        }
21457    }
21458
21459    /**
21460     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21461     * then reports the most likely home activity or null if there are more than one.
21462     */
21463    private ComponentName getDefaultHomeActivity(int userId) {
21464        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21465        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21466        if (cn != null) {
21467            return cn;
21468        }
21469
21470        // Find the launcher with the highest priority and return that component if there are no
21471        // other home activity with the same priority.
21472        int lastPriority = Integer.MIN_VALUE;
21473        ComponentName lastComponent = null;
21474        final int size = allHomeCandidates.size();
21475        for (int i = 0; i < size; i++) {
21476            final ResolveInfo ri = allHomeCandidates.get(i);
21477            if (ri.priority > lastPriority) {
21478                lastComponent = ri.activityInfo.getComponentName();
21479                lastPriority = ri.priority;
21480            } else if (ri.priority == lastPriority) {
21481                // Two components found with same priority.
21482                lastComponent = null;
21483            }
21484        }
21485        return lastComponent;
21486    }
21487
21488    private Intent getHomeIntent() {
21489        Intent intent = new Intent(Intent.ACTION_MAIN);
21490        intent.addCategory(Intent.CATEGORY_HOME);
21491        intent.addCategory(Intent.CATEGORY_DEFAULT);
21492        return intent;
21493    }
21494
21495    private IntentFilter getHomeFilter() {
21496        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21497        filter.addCategory(Intent.CATEGORY_HOME);
21498        filter.addCategory(Intent.CATEGORY_DEFAULT);
21499        return filter;
21500    }
21501
21502    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21503            int userId) {
21504        Intent intent  = getHomeIntent();
21505        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21506                PackageManager.GET_META_DATA, userId);
21507        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21508                true, false, false, userId);
21509
21510        allHomeCandidates.clear();
21511        if (list != null) {
21512            for (ResolveInfo ri : list) {
21513                allHomeCandidates.add(ri);
21514            }
21515        }
21516        return (preferred == null || preferred.activityInfo == null)
21517                ? null
21518                : new ComponentName(preferred.activityInfo.packageName,
21519                        preferred.activityInfo.name);
21520    }
21521
21522    @Override
21523    public void setHomeActivity(ComponentName comp, int userId) {
21524        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21525            return;
21526        }
21527        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21528        getHomeActivitiesAsUser(homeActivities, userId);
21529
21530        boolean found = false;
21531
21532        final int size = homeActivities.size();
21533        final ComponentName[] set = new ComponentName[size];
21534        for (int i = 0; i < size; i++) {
21535            final ResolveInfo candidate = homeActivities.get(i);
21536            final ActivityInfo info = candidate.activityInfo;
21537            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21538            set[i] = activityName;
21539            if (!found && activityName.equals(comp)) {
21540                found = true;
21541            }
21542        }
21543        if (!found) {
21544            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21545                    + userId);
21546        }
21547        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21548                set, comp, userId);
21549    }
21550
21551    private @Nullable String getSetupWizardPackageName() {
21552        final Intent intent = new Intent(Intent.ACTION_MAIN);
21553        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21554
21555        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21556                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21557                        | MATCH_DISABLED_COMPONENTS,
21558                UserHandle.myUserId());
21559        if (matches.size() == 1) {
21560            return matches.get(0).getComponentInfo().packageName;
21561        } else {
21562            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21563                    + ": matches=" + matches);
21564            return null;
21565        }
21566    }
21567
21568    private @Nullable String getStorageManagerPackageName() {
21569        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21570
21571        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21572                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21573                        | MATCH_DISABLED_COMPONENTS,
21574                UserHandle.myUserId());
21575        if (matches.size() == 1) {
21576            return matches.get(0).getComponentInfo().packageName;
21577        } else {
21578            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21579                    + matches.size() + ": matches=" + matches);
21580            return null;
21581        }
21582    }
21583
21584    @Override
21585    public void setApplicationEnabledSetting(String appPackageName,
21586            int newState, int flags, int userId, String callingPackage) {
21587        if (!sUserManager.exists(userId)) return;
21588        if (callingPackage == null) {
21589            callingPackage = Integer.toString(Binder.getCallingUid());
21590        }
21591        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21592    }
21593
21594    @Override
21595    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21596        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21597        synchronized (mPackages) {
21598            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21599            if (pkgSetting != null) {
21600                pkgSetting.setUpdateAvailable(updateAvailable);
21601            }
21602        }
21603    }
21604
21605    @Override
21606    public void setComponentEnabledSetting(ComponentName componentName,
21607            int newState, int flags, int userId) {
21608        if (!sUserManager.exists(userId)) return;
21609        setEnabledSetting(componentName.getPackageName(),
21610                componentName.getClassName(), newState, flags, userId, null);
21611    }
21612
21613    private void setEnabledSetting(final String packageName, String className, int newState,
21614            final int flags, int userId, String callingPackage) {
21615        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21616              || newState == COMPONENT_ENABLED_STATE_ENABLED
21617              || newState == COMPONENT_ENABLED_STATE_DISABLED
21618              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21619              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21620            throw new IllegalArgumentException("Invalid new component state: "
21621                    + newState);
21622        }
21623        PackageSetting pkgSetting;
21624        final int callingUid = Binder.getCallingUid();
21625        final int permission;
21626        if (callingUid == Process.SYSTEM_UID) {
21627            permission = PackageManager.PERMISSION_GRANTED;
21628        } else {
21629            permission = mContext.checkCallingOrSelfPermission(
21630                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21631        }
21632        enforceCrossUserPermission(callingUid, userId,
21633                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21634        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21635        boolean sendNow = false;
21636        boolean isApp = (className == null);
21637        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21638        String componentName = isApp ? packageName : className;
21639        int packageUid = -1;
21640        ArrayList<String> components;
21641
21642        // reader
21643        synchronized (mPackages) {
21644            pkgSetting = mSettings.mPackages.get(packageName);
21645            if (pkgSetting == null) {
21646                if (!isCallerInstantApp) {
21647                    if (className == null) {
21648                        throw new IllegalArgumentException("Unknown package: " + packageName);
21649                    }
21650                    throw new IllegalArgumentException(
21651                            "Unknown component: " + packageName + "/" + className);
21652                } else {
21653                    // throw SecurityException to prevent leaking package information
21654                    throw new SecurityException(
21655                            "Attempt to change component state; "
21656                            + "pid=" + Binder.getCallingPid()
21657                            + ", uid=" + callingUid
21658                            + (className == null
21659                                    ? ", package=" + packageName
21660                                    : ", component=" + packageName + "/" + className));
21661                }
21662            }
21663        }
21664
21665        // Limit who can change which apps
21666        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21667            // Don't allow apps that don't have permission to modify other apps
21668            if (!allowedByPermission
21669                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21670                throw new SecurityException(
21671                        "Attempt to change component state; "
21672                        + "pid=" + Binder.getCallingPid()
21673                        + ", uid=" + callingUid
21674                        + (className == null
21675                                ? ", package=" + packageName
21676                                : ", component=" + packageName + "/" + className));
21677            }
21678            // Don't allow changing protected packages.
21679            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21680                throw new SecurityException("Cannot disable a protected package: " + packageName);
21681            }
21682        }
21683
21684        synchronized (mPackages) {
21685            if (callingUid == Process.SHELL_UID
21686                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21687                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21688                // unless it is a test package.
21689                int oldState = pkgSetting.getEnabled(userId);
21690                if (className == null
21691                    &&
21692                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21693                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21694                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21695                    &&
21696                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21697                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
21698                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21699                    // ok
21700                } else {
21701                    throw new SecurityException(
21702                            "Shell cannot change component state for " + packageName + "/"
21703                            + className + " to " + newState);
21704                }
21705            }
21706            if (className == null) {
21707                // We're dealing with an application/package level state change
21708                if (pkgSetting.getEnabled(userId) == newState) {
21709                    // Nothing to do
21710                    return;
21711                }
21712                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21713                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21714                    // Don't care about who enables an app.
21715                    callingPackage = null;
21716                }
21717                pkgSetting.setEnabled(newState, userId, callingPackage);
21718                // pkgSetting.pkg.mSetEnabled = newState;
21719            } else {
21720                // We're dealing with a component level state change
21721                // First, verify that this is a valid class name.
21722                PackageParser.Package pkg = pkgSetting.pkg;
21723                if (pkg == null || !pkg.hasComponentClassName(className)) {
21724                    if (pkg != null &&
21725                            pkg.applicationInfo.targetSdkVersion >=
21726                                    Build.VERSION_CODES.JELLY_BEAN) {
21727                        throw new IllegalArgumentException("Component class " + className
21728                                + " does not exist in " + packageName);
21729                    } else {
21730                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21731                                + className + " does not exist in " + packageName);
21732                    }
21733                }
21734                switch (newState) {
21735                case COMPONENT_ENABLED_STATE_ENABLED:
21736                    if (!pkgSetting.enableComponentLPw(className, userId)) {
21737                        return;
21738                    }
21739                    break;
21740                case COMPONENT_ENABLED_STATE_DISABLED:
21741                    if (!pkgSetting.disableComponentLPw(className, userId)) {
21742                        return;
21743                    }
21744                    break;
21745                case COMPONENT_ENABLED_STATE_DEFAULT:
21746                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
21747                        return;
21748                    }
21749                    break;
21750                default:
21751                    Slog.e(TAG, "Invalid new component state: " + newState);
21752                    return;
21753                }
21754            }
21755            scheduleWritePackageRestrictionsLocked(userId);
21756            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21757            final long callingId = Binder.clearCallingIdentity();
21758            try {
21759                updateInstantAppInstallerLocked(packageName);
21760            } finally {
21761                Binder.restoreCallingIdentity(callingId);
21762            }
21763            components = mPendingBroadcasts.get(userId, packageName);
21764            final boolean newPackage = components == null;
21765            if (newPackage) {
21766                components = new ArrayList<String>();
21767            }
21768            if (!components.contains(componentName)) {
21769                components.add(componentName);
21770            }
21771            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21772                sendNow = true;
21773                // Purge entry from pending broadcast list if another one exists already
21774                // since we are sending one right away.
21775                mPendingBroadcasts.remove(userId, packageName);
21776            } else {
21777                if (newPackage) {
21778                    mPendingBroadcasts.put(userId, packageName, components);
21779                }
21780                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21781                    // Schedule a message
21782                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21783                }
21784            }
21785        }
21786
21787        long callingId = Binder.clearCallingIdentity();
21788        try {
21789            if (sendNow) {
21790                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21791                sendPackageChangedBroadcast(packageName,
21792                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21793            }
21794        } finally {
21795            Binder.restoreCallingIdentity(callingId);
21796        }
21797    }
21798
21799    @Override
21800    public void flushPackageRestrictionsAsUser(int userId) {
21801        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21802            return;
21803        }
21804        if (!sUserManager.exists(userId)) {
21805            return;
21806        }
21807        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21808                false /* checkShell */, "flushPackageRestrictions");
21809        synchronized (mPackages) {
21810            mSettings.writePackageRestrictionsLPr(userId);
21811            mDirtyUsers.remove(userId);
21812            if (mDirtyUsers.isEmpty()) {
21813                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21814            }
21815        }
21816    }
21817
21818    private void sendPackageChangedBroadcast(String packageName,
21819            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21820        if (DEBUG_INSTALL)
21821            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21822                    + componentNames);
21823        Bundle extras = new Bundle(4);
21824        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21825        String nameList[] = new String[componentNames.size()];
21826        componentNames.toArray(nameList);
21827        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21828        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21829        extras.putInt(Intent.EXTRA_UID, packageUid);
21830        // If this is not reporting a change of the overall package, then only send it
21831        // to registered receivers.  We don't want to launch a swath of apps for every
21832        // little component state change.
21833        final int flags = !componentNames.contains(packageName)
21834                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21835        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21836                new int[] {UserHandle.getUserId(packageUid)});
21837    }
21838
21839    @Override
21840    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21841        if (!sUserManager.exists(userId)) return;
21842        final int callingUid = Binder.getCallingUid();
21843        if (getInstantAppPackageName(callingUid) != null) {
21844            return;
21845        }
21846        final int permission = mContext.checkCallingOrSelfPermission(
21847                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21848        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21849        enforceCrossUserPermission(callingUid, userId,
21850                true /* requireFullPermission */, true /* checkShell */, "stop package");
21851        // writer
21852        synchronized (mPackages) {
21853            final PackageSetting ps = mSettings.mPackages.get(packageName);
21854            if (!filterAppAccessLPr(ps, callingUid, userId)
21855                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21856                            allowedByPermission, callingUid, userId)) {
21857                scheduleWritePackageRestrictionsLocked(userId);
21858            }
21859        }
21860    }
21861
21862    @Override
21863    public String getInstallerPackageName(String packageName) {
21864        final int callingUid = Binder.getCallingUid();
21865        if (getInstantAppPackageName(callingUid) != null) {
21866            return null;
21867        }
21868        // reader
21869        synchronized (mPackages) {
21870            final PackageSetting ps = mSettings.mPackages.get(packageName);
21871            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21872                return null;
21873            }
21874            return mSettings.getInstallerPackageNameLPr(packageName);
21875        }
21876    }
21877
21878    public boolean isOrphaned(String packageName) {
21879        // reader
21880        synchronized (mPackages) {
21881            return mSettings.isOrphaned(packageName);
21882        }
21883    }
21884
21885    @Override
21886    public int getApplicationEnabledSetting(String packageName, int userId) {
21887        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21888        int callingUid = Binder.getCallingUid();
21889        enforceCrossUserPermission(callingUid, userId,
21890                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21891        // reader
21892        synchronized (mPackages) {
21893            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21894                return COMPONENT_ENABLED_STATE_DISABLED;
21895            }
21896            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21897        }
21898    }
21899
21900    @Override
21901    public int getComponentEnabledSetting(ComponentName component, int userId) {
21902        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21903        int callingUid = Binder.getCallingUid();
21904        enforceCrossUserPermission(callingUid, userId,
21905                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21906        synchronized (mPackages) {
21907            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21908                    component, TYPE_UNKNOWN, userId)) {
21909                return COMPONENT_ENABLED_STATE_DISABLED;
21910            }
21911            return mSettings.getComponentEnabledSettingLPr(component, userId);
21912        }
21913    }
21914
21915    @Override
21916    public void enterSafeMode() {
21917        enforceSystemOrRoot("Only the system can request entering safe mode");
21918
21919        if (!mSystemReady) {
21920            mSafeMode = true;
21921        }
21922    }
21923
21924    @Override
21925    public void systemReady() {
21926        enforceSystemOrRoot("Only the system can claim the system is ready");
21927
21928        mSystemReady = true;
21929        final ContentResolver resolver = mContext.getContentResolver();
21930        ContentObserver co = new ContentObserver(mHandler) {
21931            @Override
21932            public void onChange(boolean selfChange) {
21933                mEphemeralAppsDisabled =
21934                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21935                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21936            }
21937        };
21938        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21939                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21940                false, co, UserHandle.USER_SYSTEM);
21941        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21942                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21943        co.onChange(true);
21944
21945        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21946        // disabled after already being started.
21947        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21948                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21949
21950        // Read the compatibilty setting when the system is ready.
21951        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21952                mContext.getContentResolver(),
21953                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21954        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21955        if (DEBUG_SETTINGS) {
21956            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21957        }
21958
21959        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21960
21961        synchronized (mPackages) {
21962            // Verify that all of the preferred activity components actually
21963            // exist.  It is possible for applications to be updated and at
21964            // that point remove a previously declared activity component that
21965            // had been set as a preferred activity.  We try to clean this up
21966            // the next time we encounter that preferred activity, but it is
21967            // possible for the user flow to never be able to return to that
21968            // situation so here we do a sanity check to make sure we haven't
21969            // left any junk around.
21970            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21971            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21972                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21973                removed.clear();
21974                for (PreferredActivity pa : pir.filterSet()) {
21975                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21976                        removed.add(pa);
21977                    }
21978                }
21979                if (removed.size() > 0) {
21980                    for (int r=0; r<removed.size(); r++) {
21981                        PreferredActivity pa = removed.get(r);
21982                        Slog.w(TAG, "Removing dangling preferred activity: "
21983                                + pa.mPref.mComponent);
21984                        pir.removeFilter(pa);
21985                    }
21986                    mSettings.writePackageRestrictionsLPr(
21987                            mSettings.mPreferredActivities.keyAt(i));
21988                }
21989            }
21990
21991            for (int userId : UserManagerService.getInstance().getUserIds()) {
21992                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21993                    grantPermissionsUserIds = ArrayUtils.appendInt(
21994                            grantPermissionsUserIds, userId);
21995                }
21996            }
21997        }
21998        sUserManager.systemReady();
21999
22000        // If we upgraded grant all default permissions before kicking off.
22001        for (int userId : grantPermissionsUserIds) {
22002            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22003        }
22004
22005        // If we did not grant default permissions, we preload from this the
22006        // default permission exceptions lazily to ensure we don't hit the
22007        // disk on a new user creation.
22008        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
22009            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
22010        }
22011
22012        // Kick off any messages waiting for system ready
22013        if (mPostSystemReadyMessages != null) {
22014            for (Message msg : mPostSystemReadyMessages) {
22015                msg.sendToTarget();
22016            }
22017            mPostSystemReadyMessages = null;
22018        }
22019
22020        // Watch for external volumes that come and go over time
22021        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22022        storage.registerListener(mStorageListener);
22023
22024        mInstallerService.systemReady();
22025        mPackageDexOptimizer.systemReady();
22026
22027        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
22028                StorageManagerInternal.class);
22029        StorageManagerInternal.addExternalStoragePolicy(
22030                new StorageManagerInternal.ExternalStorageMountPolicy() {
22031            @Override
22032            public int getMountMode(int uid, String packageName) {
22033                if (Process.isIsolated(uid)) {
22034                    return Zygote.MOUNT_EXTERNAL_NONE;
22035                }
22036                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
22037                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22038                }
22039                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22040                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
22041                }
22042                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
22043                    return Zygote.MOUNT_EXTERNAL_READ;
22044                }
22045                return Zygote.MOUNT_EXTERNAL_WRITE;
22046            }
22047
22048            @Override
22049            public boolean hasExternalStorage(int uid, String packageName) {
22050                return true;
22051            }
22052        });
22053
22054        // Now that we're mostly running, clean up stale users and apps
22055        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
22056        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
22057
22058        if (mPrivappPermissionsViolations != null) {
22059            Slog.wtf(TAG,"Signature|privileged permissions not in "
22060                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
22061            mPrivappPermissionsViolations = null;
22062        }
22063    }
22064
22065    public void waitForAppDataPrepared() {
22066        if (mPrepareAppDataFuture == null) {
22067            return;
22068        }
22069        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
22070        mPrepareAppDataFuture = null;
22071    }
22072
22073    @Override
22074    public boolean isSafeMode() {
22075        // allow instant applications
22076        return mSafeMode;
22077    }
22078
22079    @Override
22080    public boolean hasSystemUidErrors() {
22081        // allow instant applications
22082        return mHasSystemUidErrors;
22083    }
22084
22085    static String arrayToString(int[] array) {
22086        StringBuffer buf = new StringBuffer(128);
22087        buf.append('[');
22088        if (array != null) {
22089            for (int i=0; i<array.length; i++) {
22090                if (i > 0) buf.append(", ");
22091                buf.append(array[i]);
22092            }
22093        }
22094        buf.append(']');
22095        return buf.toString();
22096    }
22097
22098    static class DumpState {
22099        public static final int DUMP_LIBS = 1 << 0;
22100        public static final int DUMP_FEATURES = 1 << 1;
22101        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
22102        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
22103        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
22104        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
22105        public static final int DUMP_PERMISSIONS = 1 << 6;
22106        public static final int DUMP_PACKAGES = 1 << 7;
22107        public static final int DUMP_SHARED_USERS = 1 << 8;
22108        public static final int DUMP_MESSAGES = 1 << 9;
22109        public static final int DUMP_PROVIDERS = 1 << 10;
22110        public static final int DUMP_VERIFIERS = 1 << 11;
22111        public static final int DUMP_PREFERRED = 1 << 12;
22112        public static final int DUMP_PREFERRED_XML = 1 << 13;
22113        public static final int DUMP_KEYSETS = 1 << 14;
22114        public static final int DUMP_VERSION = 1 << 15;
22115        public static final int DUMP_INSTALLS = 1 << 16;
22116        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
22117        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
22118        public static final int DUMP_FROZEN = 1 << 19;
22119        public static final int DUMP_DEXOPT = 1 << 20;
22120        public static final int DUMP_COMPILER_STATS = 1 << 21;
22121        public static final int DUMP_CHANGES = 1 << 22;
22122        public static final int DUMP_VOLUMES = 1 << 23;
22123
22124        public static final int OPTION_SHOW_FILTERS = 1 << 0;
22125
22126        private int mTypes;
22127
22128        private int mOptions;
22129
22130        private boolean mTitlePrinted;
22131
22132        private SharedUserSetting mSharedUser;
22133
22134        public boolean isDumping(int type) {
22135            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
22136                return true;
22137            }
22138
22139            return (mTypes & type) != 0;
22140        }
22141
22142        public void setDump(int type) {
22143            mTypes |= type;
22144        }
22145
22146        public boolean isOptionEnabled(int option) {
22147            return (mOptions & option) != 0;
22148        }
22149
22150        public void setOptionEnabled(int option) {
22151            mOptions |= option;
22152        }
22153
22154        public boolean onTitlePrinted() {
22155            final boolean printed = mTitlePrinted;
22156            mTitlePrinted = true;
22157            return printed;
22158        }
22159
22160        public boolean getTitlePrinted() {
22161            return mTitlePrinted;
22162        }
22163
22164        public void setTitlePrinted(boolean enabled) {
22165            mTitlePrinted = enabled;
22166        }
22167
22168        public SharedUserSetting getSharedUser() {
22169            return mSharedUser;
22170        }
22171
22172        public void setSharedUser(SharedUserSetting user) {
22173            mSharedUser = user;
22174        }
22175    }
22176
22177    @Override
22178    public void onShellCommand(FileDescriptor in, FileDescriptor out,
22179            FileDescriptor err, String[] args, ShellCallback callback,
22180            ResultReceiver resultReceiver) {
22181        (new PackageManagerShellCommand(this)).exec(
22182                this, in, out, err, args, callback, resultReceiver);
22183    }
22184
22185    @Override
22186    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
22187        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
22188
22189        DumpState dumpState = new DumpState();
22190        boolean fullPreferred = false;
22191        boolean checkin = false;
22192
22193        String packageName = null;
22194        ArraySet<String> permissionNames = null;
22195
22196        int opti = 0;
22197        while (opti < args.length) {
22198            String opt = args[opti];
22199            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
22200                break;
22201            }
22202            opti++;
22203
22204            if ("-a".equals(opt)) {
22205                // Right now we only know how to print all.
22206            } else if ("-h".equals(opt)) {
22207                pw.println("Package manager dump options:");
22208                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
22209                pw.println("    --checkin: dump for a checkin");
22210                pw.println("    -f: print details of intent filters");
22211                pw.println("    -h: print this help");
22212                pw.println("  cmd may be one of:");
22213                pw.println("    l[ibraries]: list known shared libraries");
22214                pw.println("    f[eatures]: list device features");
22215                pw.println("    k[eysets]: print known keysets");
22216                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
22217                pw.println("    perm[issions]: dump permissions");
22218                pw.println("    permission [name ...]: dump declaration and use of given permission");
22219                pw.println("    pref[erred]: print preferred package settings");
22220                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
22221                pw.println("    prov[iders]: dump content providers");
22222                pw.println("    p[ackages]: dump installed packages");
22223                pw.println("    s[hared-users]: dump shared user IDs");
22224                pw.println("    m[essages]: print collected runtime messages");
22225                pw.println("    v[erifiers]: print package verifier info");
22226                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
22227                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
22228                pw.println("    version: print database version info");
22229                pw.println("    write: write current settings now");
22230                pw.println("    installs: details about install sessions");
22231                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
22232                pw.println("    dexopt: dump dexopt state");
22233                pw.println("    compiler-stats: dump compiler statistics");
22234                pw.println("    enabled-overlays: dump list of enabled overlay packages");
22235                pw.println("    <package.name>: info about given package");
22236                return;
22237            } else if ("--checkin".equals(opt)) {
22238                checkin = true;
22239            } else if ("-f".equals(opt)) {
22240                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22241            } else if ("--proto".equals(opt)) {
22242                dumpProto(fd);
22243                return;
22244            } else {
22245                pw.println("Unknown argument: " + opt + "; use -h for help");
22246            }
22247        }
22248
22249        // Is the caller requesting to dump a particular piece of data?
22250        if (opti < args.length) {
22251            String cmd = args[opti];
22252            opti++;
22253            // Is this a package name?
22254            if ("android".equals(cmd) || cmd.contains(".")) {
22255                packageName = cmd;
22256                // When dumping a single package, we always dump all of its
22257                // filter information since the amount of data will be reasonable.
22258                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22259            } else if ("check-permission".equals(cmd)) {
22260                if (opti >= args.length) {
22261                    pw.println("Error: check-permission missing permission argument");
22262                    return;
22263                }
22264                String perm = args[opti];
22265                opti++;
22266                if (opti >= args.length) {
22267                    pw.println("Error: check-permission missing package argument");
22268                    return;
22269                }
22270
22271                String pkg = args[opti];
22272                opti++;
22273                int user = UserHandle.getUserId(Binder.getCallingUid());
22274                if (opti < args.length) {
22275                    try {
22276                        user = Integer.parseInt(args[opti]);
22277                    } catch (NumberFormatException e) {
22278                        pw.println("Error: check-permission user argument is not a number: "
22279                                + args[opti]);
22280                        return;
22281                    }
22282                }
22283
22284                // Normalize package name to handle renamed packages and static libs
22285                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
22286
22287                pw.println(checkPermission(perm, pkg, user));
22288                return;
22289            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
22290                dumpState.setDump(DumpState.DUMP_LIBS);
22291            } else if ("f".equals(cmd) || "features".equals(cmd)) {
22292                dumpState.setDump(DumpState.DUMP_FEATURES);
22293            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
22294                if (opti >= args.length) {
22295                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
22296                            | DumpState.DUMP_SERVICE_RESOLVERS
22297                            | DumpState.DUMP_RECEIVER_RESOLVERS
22298                            | DumpState.DUMP_CONTENT_RESOLVERS);
22299                } else {
22300                    while (opti < args.length) {
22301                        String name = args[opti];
22302                        if ("a".equals(name) || "activity".equals(name)) {
22303                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
22304                        } else if ("s".equals(name) || "service".equals(name)) {
22305                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
22306                        } else if ("r".equals(name) || "receiver".equals(name)) {
22307                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
22308                        } else if ("c".equals(name) || "content".equals(name)) {
22309                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
22310                        } else {
22311                            pw.println("Error: unknown resolver table type: " + name);
22312                            return;
22313                        }
22314                        opti++;
22315                    }
22316                }
22317            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
22318                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
22319            } else if ("permission".equals(cmd)) {
22320                if (opti >= args.length) {
22321                    pw.println("Error: permission requires permission name");
22322                    return;
22323                }
22324                permissionNames = new ArraySet<>();
22325                while (opti < args.length) {
22326                    permissionNames.add(args[opti]);
22327                    opti++;
22328                }
22329                dumpState.setDump(DumpState.DUMP_PERMISSIONS
22330                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
22331            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
22332                dumpState.setDump(DumpState.DUMP_PREFERRED);
22333            } else if ("preferred-xml".equals(cmd)) {
22334                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
22335                if (opti < args.length && "--full".equals(args[opti])) {
22336                    fullPreferred = true;
22337                    opti++;
22338                }
22339            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
22340                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
22341            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
22342                dumpState.setDump(DumpState.DUMP_PACKAGES);
22343            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
22344                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
22345            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
22346                dumpState.setDump(DumpState.DUMP_PROVIDERS);
22347            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
22348                dumpState.setDump(DumpState.DUMP_MESSAGES);
22349            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
22350                dumpState.setDump(DumpState.DUMP_VERIFIERS);
22351            } else if ("i".equals(cmd) || "ifv".equals(cmd)
22352                    || "intent-filter-verifiers".equals(cmd)) {
22353                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
22354            } else if ("version".equals(cmd)) {
22355                dumpState.setDump(DumpState.DUMP_VERSION);
22356            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
22357                dumpState.setDump(DumpState.DUMP_KEYSETS);
22358            } else if ("installs".equals(cmd)) {
22359                dumpState.setDump(DumpState.DUMP_INSTALLS);
22360            } else if ("frozen".equals(cmd)) {
22361                dumpState.setDump(DumpState.DUMP_FROZEN);
22362            } else if ("volumes".equals(cmd)) {
22363                dumpState.setDump(DumpState.DUMP_VOLUMES);
22364            } else if ("dexopt".equals(cmd)) {
22365                dumpState.setDump(DumpState.DUMP_DEXOPT);
22366            } else if ("compiler-stats".equals(cmd)) {
22367                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
22368            } else if ("changes".equals(cmd)) {
22369                dumpState.setDump(DumpState.DUMP_CHANGES);
22370            } else if ("write".equals(cmd)) {
22371                synchronized (mPackages) {
22372                    mSettings.writeLPr();
22373                    pw.println("Settings written.");
22374                    return;
22375                }
22376            }
22377        }
22378
22379        if (checkin) {
22380            pw.println("vers,1");
22381        }
22382
22383        // reader
22384        synchronized (mPackages) {
22385            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
22386                if (!checkin) {
22387                    if (dumpState.onTitlePrinted())
22388                        pw.println();
22389                    pw.println("Database versions:");
22390                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22391                }
22392            }
22393
22394            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22395                if (!checkin) {
22396                    if (dumpState.onTitlePrinted())
22397                        pw.println();
22398                    pw.println("Verifiers:");
22399                    pw.print("  Required: ");
22400                    pw.print(mRequiredVerifierPackage);
22401                    pw.print(" (uid=");
22402                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22403                            UserHandle.USER_SYSTEM));
22404                    pw.println(")");
22405                } else if (mRequiredVerifierPackage != null) {
22406                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22407                    pw.print(",");
22408                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22409                            UserHandle.USER_SYSTEM));
22410                }
22411            }
22412
22413            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22414                    packageName == null) {
22415                if (mIntentFilterVerifierComponent != null) {
22416                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22417                    if (!checkin) {
22418                        if (dumpState.onTitlePrinted())
22419                            pw.println();
22420                        pw.println("Intent Filter Verifier:");
22421                        pw.print("  Using: ");
22422                        pw.print(verifierPackageName);
22423                        pw.print(" (uid=");
22424                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22425                                UserHandle.USER_SYSTEM));
22426                        pw.println(")");
22427                    } else if (verifierPackageName != null) {
22428                        pw.print("ifv,"); pw.print(verifierPackageName);
22429                        pw.print(",");
22430                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22431                                UserHandle.USER_SYSTEM));
22432                    }
22433                } else {
22434                    pw.println();
22435                    pw.println("No Intent Filter Verifier available!");
22436                }
22437            }
22438
22439            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22440                boolean printedHeader = false;
22441                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22442                while (it.hasNext()) {
22443                    String libName = it.next();
22444                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22445                    if (versionedLib == null) {
22446                        continue;
22447                    }
22448                    final int versionCount = versionedLib.size();
22449                    for (int i = 0; i < versionCount; i++) {
22450                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22451                        if (!checkin) {
22452                            if (!printedHeader) {
22453                                if (dumpState.onTitlePrinted())
22454                                    pw.println();
22455                                pw.println("Libraries:");
22456                                printedHeader = true;
22457                            }
22458                            pw.print("  ");
22459                        } else {
22460                            pw.print("lib,");
22461                        }
22462                        pw.print(libEntry.info.getName());
22463                        if (libEntry.info.isStatic()) {
22464                            pw.print(" version=" + libEntry.info.getVersion());
22465                        }
22466                        if (!checkin) {
22467                            pw.print(" -> ");
22468                        }
22469                        if (libEntry.path != null) {
22470                            pw.print(" (jar) ");
22471                            pw.print(libEntry.path);
22472                        } else {
22473                            pw.print(" (apk) ");
22474                            pw.print(libEntry.apk);
22475                        }
22476                        pw.println();
22477                    }
22478                }
22479            }
22480
22481            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22482                if (dumpState.onTitlePrinted())
22483                    pw.println();
22484                if (!checkin) {
22485                    pw.println("Features:");
22486                }
22487
22488                synchronized (mAvailableFeatures) {
22489                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22490                        if (checkin) {
22491                            pw.print("feat,");
22492                            pw.print(feat.name);
22493                            pw.print(",");
22494                            pw.println(feat.version);
22495                        } else {
22496                            pw.print("  ");
22497                            pw.print(feat.name);
22498                            if (feat.version > 0) {
22499                                pw.print(" version=");
22500                                pw.print(feat.version);
22501                            }
22502                            pw.println();
22503                        }
22504                    }
22505                }
22506            }
22507
22508            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22509                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22510                        : "Activity Resolver Table:", "  ", packageName,
22511                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22512                    dumpState.setTitlePrinted(true);
22513                }
22514            }
22515            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22516                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22517                        : "Receiver Resolver Table:", "  ", packageName,
22518                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22519                    dumpState.setTitlePrinted(true);
22520                }
22521            }
22522            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22523                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22524                        : "Service Resolver Table:", "  ", packageName,
22525                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22526                    dumpState.setTitlePrinted(true);
22527                }
22528            }
22529            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22530                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22531                        : "Provider Resolver Table:", "  ", packageName,
22532                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22533                    dumpState.setTitlePrinted(true);
22534                }
22535            }
22536
22537            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22538                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22539                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22540                    int user = mSettings.mPreferredActivities.keyAt(i);
22541                    if (pir.dump(pw,
22542                            dumpState.getTitlePrinted()
22543                                ? "\nPreferred Activities User " + user + ":"
22544                                : "Preferred Activities User " + user + ":", "  ",
22545                            packageName, true, false)) {
22546                        dumpState.setTitlePrinted(true);
22547                    }
22548                }
22549            }
22550
22551            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22552                pw.flush();
22553                FileOutputStream fout = new FileOutputStream(fd);
22554                BufferedOutputStream str = new BufferedOutputStream(fout);
22555                XmlSerializer serializer = new FastXmlSerializer();
22556                try {
22557                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22558                    serializer.startDocument(null, true);
22559                    serializer.setFeature(
22560                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22561                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22562                    serializer.endDocument();
22563                    serializer.flush();
22564                } catch (IllegalArgumentException e) {
22565                    pw.println("Failed writing: " + e);
22566                } catch (IllegalStateException e) {
22567                    pw.println("Failed writing: " + e);
22568                } catch (IOException e) {
22569                    pw.println("Failed writing: " + e);
22570                }
22571            }
22572
22573            if (!checkin
22574                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22575                    && packageName == null) {
22576                pw.println();
22577                int count = mSettings.mPackages.size();
22578                if (count == 0) {
22579                    pw.println("No applications!");
22580                    pw.println();
22581                } else {
22582                    final String prefix = "  ";
22583                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22584                    if (allPackageSettings.size() == 0) {
22585                        pw.println("No domain preferred apps!");
22586                        pw.println();
22587                    } else {
22588                        pw.println("App verification status:");
22589                        pw.println();
22590                        count = 0;
22591                        for (PackageSetting ps : allPackageSettings) {
22592                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22593                            if (ivi == null || ivi.getPackageName() == null) continue;
22594                            pw.println(prefix + "Package: " + ivi.getPackageName());
22595                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22596                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22597                            pw.println();
22598                            count++;
22599                        }
22600                        if (count == 0) {
22601                            pw.println(prefix + "No app verification established.");
22602                            pw.println();
22603                        }
22604                        for (int userId : sUserManager.getUserIds()) {
22605                            pw.println("App linkages for user " + userId + ":");
22606                            pw.println();
22607                            count = 0;
22608                            for (PackageSetting ps : allPackageSettings) {
22609                                final long status = ps.getDomainVerificationStatusForUser(userId);
22610                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22611                                        && !DEBUG_DOMAIN_VERIFICATION) {
22612                                    continue;
22613                                }
22614                                pw.println(prefix + "Package: " + ps.name);
22615                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22616                                String statusStr = IntentFilterVerificationInfo.
22617                                        getStatusStringFromValue(status);
22618                                pw.println(prefix + "Status:  " + statusStr);
22619                                pw.println();
22620                                count++;
22621                            }
22622                            if (count == 0) {
22623                                pw.println(prefix + "No configured app linkages.");
22624                                pw.println();
22625                            }
22626                        }
22627                    }
22628                }
22629            }
22630
22631            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22632                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22633                if (packageName == null && permissionNames == null) {
22634                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22635                        if (iperm == 0) {
22636                            if (dumpState.onTitlePrinted())
22637                                pw.println();
22638                            pw.println("AppOp Permissions:");
22639                        }
22640                        pw.print("  AppOp Permission ");
22641                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22642                        pw.println(":");
22643                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22644                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22645                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22646                        }
22647                    }
22648                }
22649            }
22650
22651            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22652                boolean printedSomething = false;
22653                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22654                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22655                        continue;
22656                    }
22657                    if (!printedSomething) {
22658                        if (dumpState.onTitlePrinted())
22659                            pw.println();
22660                        pw.println("Registered ContentProviders:");
22661                        printedSomething = true;
22662                    }
22663                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22664                    pw.print("    "); pw.println(p.toString());
22665                }
22666                printedSomething = false;
22667                for (Map.Entry<String, PackageParser.Provider> entry :
22668                        mProvidersByAuthority.entrySet()) {
22669                    PackageParser.Provider p = entry.getValue();
22670                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22671                        continue;
22672                    }
22673                    if (!printedSomething) {
22674                        if (dumpState.onTitlePrinted())
22675                            pw.println();
22676                        pw.println("ContentProvider Authorities:");
22677                        printedSomething = true;
22678                    }
22679                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22680                    pw.print("    "); pw.println(p.toString());
22681                    if (p.info != null && p.info.applicationInfo != null) {
22682                        final String appInfo = p.info.applicationInfo.toString();
22683                        pw.print("      applicationInfo="); pw.println(appInfo);
22684                    }
22685                }
22686            }
22687
22688            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22689                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22690            }
22691
22692            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22693                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22694            }
22695
22696            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22697                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22698            }
22699
22700            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22701                if (dumpState.onTitlePrinted()) pw.println();
22702                pw.println("Package Changes:");
22703                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22704                final int K = mChangedPackages.size();
22705                for (int i = 0; i < K; i++) {
22706                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22707                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22708                    final int N = changes.size();
22709                    if (N == 0) {
22710                        pw.print("    "); pw.println("No packages changed");
22711                    } else {
22712                        for (int j = 0; j < N; j++) {
22713                            final String pkgName = changes.valueAt(j);
22714                            final int sequenceNumber = changes.keyAt(j);
22715                            pw.print("    ");
22716                            pw.print("seq=");
22717                            pw.print(sequenceNumber);
22718                            pw.print(", package=");
22719                            pw.println(pkgName);
22720                        }
22721                    }
22722                }
22723            }
22724
22725            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22726                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22727            }
22728
22729            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22730                // XXX should handle packageName != null by dumping only install data that
22731                // the given package is involved with.
22732                if (dumpState.onTitlePrinted()) pw.println();
22733
22734                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22735                ipw.println();
22736                ipw.println("Frozen packages:");
22737                ipw.increaseIndent();
22738                if (mFrozenPackages.size() == 0) {
22739                    ipw.println("(none)");
22740                } else {
22741                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22742                        ipw.println(mFrozenPackages.valueAt(i));
22743                    }
22744                }
22745                ipw.decreaseIndent();
22746            }
22747
22748            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
22749                if (dumpState.onTitlePrinted()) pw.println();
22750
22751                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22752                ipw.println();
22753                ipw.println("Loaded volumes:");
22754                ipw.increaseIndent();
22755                if (mLoadedVolumes.size() == 0) {
22756                    ipw.println("(none)");
22757                } else {
22758                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
22759                        ipw.println(mLoadedVolumes.valueAt(i));
22760                    }
22761                }
22762                ipw.decreaseIndent();
22763            }
22764
22765            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22766                if (dumpState.onTitlePrinted()) pw.println();
22767                dumpDexoptStateLPr(pw, packageName);
22768            }
22769
22770            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22771                if (dumpState.onTitlePrinted()) pw.println();
22772                dumpCompilerStatsLPr(pw, packageName);
22773            }
22774
22775            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22776                if (dumpState.onTitlePrinted()) pw.println();
22777                mSettings.dumpReadMessagesLPr(pw, dumpState);
22778
22779                pw.println();
22780                pw.println("Package warning messages:");
22781                BufferedReader in = null;
22782                String line = null;
22783                try {
22784                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22785                    while ((line = in.readLine()) != null) {
22786                        if (line.contains("ignored: updated version")) continue;
22787                        pw.println(line);
22788                    }
22789                } catch (IOException ignored) {
22790                } finally {
22791                    IoUtils.closeQuietly(in);
22792                }
22793            }
22794
22795            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22796                BufferedReader in = null;
22797                String line = null;
22798                try {
22799                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22800                    while ((line = in.readLine()) != null) {
22801                        if (line.contains("ignored: updated version")) continue;
22802                        pw.print("msg,");
22803                        pw.println(line);
22804                    }
22805                } catch (IOException ignored) {
22806                } finally {
22807                    IoUtils.closeQuietly(in);
22808                }
22809            }
22810        }
22811
22812        // PackageInstaller should be called outside of mPackages lock
22813        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22814            // XXX should handle packageName != null by dumping only install data that
22815            // the given package is involved with.
22816            if (dumpState.onTitlePrinted()) pw.println();
22817            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22818        }
22819    }
22820
22821    private void dumpProto(FileDescriptor fd) {
22822        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22823
22824        synchronized (mPackages) {
22825            final long requiredVerifierPackageToken =
22826                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22827            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22828            proto.write(
22829                    PackageServiceDumpProto.PackageShortProto.UID,
22830                    getPackageUid(
22831                            mRequiredVerifierPackage,
22832                            MATCH_DEBUG_TRIAGED_MISSING,
22833                            UserHandle.USER_SYSTEM));
22834            proto.end(requiredVerifierPackageToken);
22835
22836            if (mIntentFilterVerifierComponent != null) {
22837                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22838                final long verifierPackageToken =
22839                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22840                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22841                proto.write(
22842                        PackageServiceDumpProto.PackageShortProto.UID,
22843                        getPackageUid(
22844                                verifierPackageName,
22845                                MATCH_DEBUG_TRIAGED_MISSING,
22846                                UserHandle.USER_SYSTEM));
22847                proto.end(verifierPackageToken);
22848            }
22849
22850            dumpSharedLibrariesProto(proto);
22851            dumpFeaturesProto(proto);
22852            mSettings.dumpPackagesProto(proto);
22853            mSettings.dumpSharedUsersProto(proto);
22854            dumpMessagesProto(proto);
22855        }
22856        proto.flush();
22857    }
22858
22859    private void dumpMessagesProto(ProtoOutputStream proto) {
22860        BufferedReader in = null;
22861        String line = null;
22862        try {
22863            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22864            while ((line = in.readLine()) != null) {
22865                if (line.contains("ignored: updated version")) continue;
22866                proto.write(PackageServiceDumpProto.MESSAGES, line);
22867            }
22868        } catch (IOException ignored) {
22869        } finally {
22870            IoUtils.closeQuietly(in);
22871        }
22872    }
22873
22874    private void dumpFeaturesProto(ProtoOutputStream proto) {
22875        synchronized (mAvailableFeatures) {
22876            final int count = mAvailableFeatures.size();
22877            for (int i = 0; i < count; i++) {
22878                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22879                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22880                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22881                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22882                proto.end(featureToken);
22883            }
22884        }
22885    }
22886
22887    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22888        final int count = mSharedLibraries.size();
22889        for (int i = 0; i < count; i++) {
22890            final String libName = mSharedLibraries.keyAt(i);
22891            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22892            if (versionedLib == null) {
22893                continue;
22894            }
22895            final int versionCount = versionedLib.size();
22896            for (int j = 0; j < versionCount; j++) {
22897                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22898                final long sharedLibraryToken =
22899                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22900                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22901                final boolean isJar = (libEntry.path != null);
22902                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22903                if (isJar) {
22904                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22905                } else {
22906                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22907                }
22908                proto.end(sharedLibraryToken);
22909            }
22910        }
22911    }
22912
22913    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22914        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22915        ipw.println();
22916        ipw.println("Dexopt state:");
22917        ipw.increaseIndent();
22918        Collection<PackageParser.Package> packages = null;
22919        if (packageName != null) {
22920            PackageParser.Package targetPackage = mPackages.get(packageName);
22921            if (targetPackage != null) {
22922                packages = Collections.singletonList(targetPackage);
22923            } else {
22924                ipw.println("Unable to find package: " + packageName);
22925                return;
22926            }
22927        } else {
22928            packages = mPackages.values();
22929        }
22930
22931        for (PackageParser.Package pkg : packages) {
22932            ipw.println("[" + pkg.packageName + "]");
22933            ipw.increaseIndent();
22934            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
22935                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
22936            ipw.decreaseIndent();
22937        }
22938    }
22939
22940    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22941        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22942        ipw.println();
22943        ipw.println("Compiler stats:");
22944        ipw.increaseIndent();
22945        Collection<PackageParser.Package> packages = null;
22946        if (packageName != null) {
22947            PackageParser.Package targetPackage = mPackages.get(packageName);
22948            if (targetPackage != null) {
22949                packages = Collections.singletonList(targetPackage);
22950            } else {
22951                ipw.println("Unable to find package: " + packageName);
22952                return;
22953            }
22954        } else {
22955            packages = mPackages.values();
22956        }
22957
22958        for (PackageParser.Package pkg : packages) {
22959            ipw.println("[" + pkg.packageName + "]");
22960            ipw.increaseIndent();
22961
22962            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22963            if (stats == null) {
22964                ipw.println("(No recorded stats)");
22965            } else {
22966                stats.dump(ipw);
22967            }
22968            ipw.decreaseIndent();
22969        }
22970    }
22971
22972    private String dumpDomainString(String packageName) {
22973        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22974                .getList();
22975        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22976
22977        ArraySet<String> result = new ArraySet<>();
22978        if (iviList.size() > 0) {
22979            for (IntentFilterVerificationInfo ivi : iviList) {
22980                for (String host : ivi.getDomains()) {
22981                    result.add(host);
22982                }
22983            }
22984        }
22985        if (filters != null && filters.size() > 0) {
22986            for (IntentFilter filter : filters) {
22987                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22988                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22989                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22990                    result.addAll(filter.getHostsList());
22991                }
22992            }
22993        }
22994
22995        StringBuilder sb = new StringBuilder(result.size() * 16);
22996        for (String domain : result) {
22997            if (sb.length() > 0) sb.append(" ");
22998            sb.append(domain);
22999        }
23000        return sb.toString();
23001    }
23002
23003    // ------- apps on sdcard specific code -------
23004    static final boolean DEBUG_SD_INSTALL = false;
23005
23006    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
23007
23008    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
23009
23010    private boolean mMediaMounted = false;
23011
23012    static String getEncryptKey() {
23013        try {
23014            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
23015                    SD_ENCRYPTION_KEYSTORE_NAME);
23016            if (sdEncKey == null) {
23017                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
23018                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
23019                if (sdEncKey == null) {
23020                    Slog.e(TAG, "Failed to create encryption keys");
23021                    return null;
23022                }
23023            }
23024            return sdEncKey;
23025        } catch (NoSuchAlgorithmException nsae) {
23026            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
23027            return null;
23028        } catch (IOException ioe) {
23029            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
23030            return null;
23031        }
23032    }
23033
23034    /*
23035     * Update media status on PackageManager.
23036     */
23037    @Override
23038    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
23039        enforceSystemOrRoot("Media status can only be updated by the system");
23040        // reader; this apparently protects mMediaMounted, but should probably
23041        // be a different lock in that case.
23042        synchronized (mPackages) {
23043            Log.i(TAG, "Updating external media status from "
23044                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
23045                    + (mediaStatus ? "mounted" : "unmounted"));
23046            if (DEBUG_SD_INSTALL)
23047                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
23048                        + ", mMediaMounted=" + mMediaMounted);
23049            if (mediaStatus == mMediaMounted) {
23050                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
23051                        : 0, -1);
23052                mHandler.sendMessage(msg);
23053                return;
23054            }
23055            mMediaMounted = mediaStatus;
23056        }
23057        // Queue up an async operation since the package installation may take a
23058        // little while.
23059        mHandler.post(new Runnable() {
23060            public void run() {
23061                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
23062            }
23063        });
23064    }
23065
23066    /**
23067     * Called by StorageManagerService when the initial ASECs to scan are available.
23068     * Should block until all the ASEC containers are finished being scanned.
23069     */
23070    public void scanAvailableAsecs() {
23071        updateExternalMediaStatusInner(true, false, false);
23072    }
23073
23074    /*
23075     * Collect information of applications on external media, map them against
23076     * existing containers and update information based on current mount status.
23077     * Please note that we always have to report status if reportStatus has been
23078     * set to true especially when unloading packages.
23079     */
23080    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
23081            boolean externalStorage) {
23082        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
23083        int[] uidArr = EmptyArray.INT;
23084
23085        final String[] list = PackageHelper.getSecureContainerList();
23086        if (ArrayUtils.isEmpty(list)) {
23087            Log.i(TAG, "No secure containers found");
23088        } else {
23089            // Process list of secure containers and categorize them
23090            // as active or stale based on their package internal state.
23091
23092            // reader
23093            synchronized (mPackages) {
23094                for (String cid : list) {
23095                    // Leave stages untouched for now; installer service owns them
23096                    if (PackageInstallerService.isStageName(cid)) continue;
23097
23098                    if (DEBUG_SD_INSTALL)
23099                        Log.i(TAG, "Processing container " + cid);
23100                    String pkgName = getAsecPackageName(cid);
23101                    if (pkgName == null) {
23102                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
23103                        continue;
23104                    }
23105                    if (DEBUG_SD_INSTALL)
23106                        Log.i(TAG, "Looking for pkg : " + pkgName);
23107
23108                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
23109                    if (ps == null) {
23110                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
23111                        continue;
23112                    }
23113
23114                    /*
23115                     * Skip packages that are not external if we're unmounting
23116                     * external storage.
23117                     */
23118                    if (externalStorage && !isMounted && !isExternal(ps)) {
23119                        continue;
23120                    }
23121
23122                    final AsecInstallArgs args = new AsecInstallArgs(cid,
23123                            getAppDexInstructionSets(ps), ps.isForwardLocked());
23124                    // The package status is changed only if the code path
23125                    // matches between settings and the container id.
23126                    if (ps.codePathString != null
23127                            && ps.codePathString.startsWith(args.getCodePath())) {
23128                        if (DEBUG_SD_INSTALL) {
23129                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
23130                                    + " at code path: " + ps.codePathString);
23131                        }
23132
23133                        // We do have a valid package installed on sdcard
23134                        processCids.put(args, ps.codePathString);
23135                        final int uid = ps.appId;
23136                        if (uid != -1) {
23137                            uidArr = ArrayUtils.appendInt(uidArr, uid);
23138                        }
23139                    } else {
23140                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
23141                                + ps.codePathString);
23142                    }
23143                }
23144            }
23145
23146            Arrays.sort(uidArr);
23147        }
23148
23149        // Process packages with valid entries.
23150        if (isMounted) {
23151            if (DEBUG_SD_INSTALL)
23152                Log.i(TAG, "Loading packages");
23153            loadMediaPackages(processCids, uidArr, externalStorage);
23154            startCleaningPackages();
23155            mInstallerService.onSecureContainersAvailable();
23156        } else {
23157            if (DEBUG_SD_INSTALL)
23158                Log.i(TAG, "Unloading packages");
23159            unloadMediaPackages(processCids, uidArr, reportStatus);
23160        }
23161    }
23162
23163    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23164            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
23165        final int size = infos.size();
23166        final String[] packageNames = new String[size];
23167        final int[] packageUids = new int[size];
23168        for (int i = 0; i < size; i++) {
23169            final ApplicationInfo info = infos.get(i);
23170            packageNames[i] = info.packageName;
23171            packageUids[i] = info.uid;
23172        }
23173        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
23174                finishedReceiver);
23175    }
23176
23177    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23178            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23179        sendResourcesChangedBroadcast(mediaStatus, replacing,
23180                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
23181    }
23182
23183    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23184            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23185        int size = pkgList.length;
23186        if (size > 0) {
23187            // Send broadcasts here
23188            Bundle extras = new Bundle();
23189            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
23190            if (uidArr != null) {
23191                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
23192            }
23193            if (replacing) {
23194                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
23195            }
23196            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
23197                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
23198            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
23199        }
23200    }
23201
23202   /*
23203     * Look at potentially valid container ids from processCids If package
23204     * information doesn't match the one on record or package scanning fails,
23205     * the cid is added to list of removeCids. We currently don't delete stale
23206     * containers.
23207     */
23208    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
23209            boolean externalStorage) {
23210        ArrayList<String> pkgList = new ArrayList<String>();
23211        Set<AsecInstallArgs> keys = processCids.keySet();
23212
23213        for (AsecInstallArgs args : keys) {
23214            String codePath = processCids.get(args);
23215            if (DEBUG_SD_INSTALL)
23216                Log.i(TAG, "Loading container : " + args.cid);
23217            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
23218            try {
23219                // Make sure there are no container errors first.
23220                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
23221                    Slog.e(TAG, "Failed to mount cid : " + args.cid
23222                            + " when installing from sdcard");
23223                    continue;
23224                }
23225                // Check code path here.
23226                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
23227                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
23228                            + " does not match one in settings " + codePath);
23229                    continue;
23230                }
23231                // Parse package
23232                int parseFlags = mDefParseFlags;
23233                if (args.isExternalAsec()) {
23234                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
23235                }
23236                if (args.isFwdLocked()) {
23237                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
23238                }
23239
23240                synchronized (mInstallLock) {
23241                    PackageParser.Package pkg = null;
23242                    try {
23243                        // Sadly we don't know the package name yet to freeze it
23244                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
23245                                SCAN_IGNORE_FROZEN, 0, null);
23246                    } catch (PackageManagerException e) {
23247                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
23248                    }
23249                    // Scan the package
23250                    if (pkg != null) {
23251                        /*
23252                         * TODO why is the lock being held? doPostInstall is
23253                         * called in other places without the lock. This needs
23254                         * to be straightened out.
23255                         */
23256                        // writer
23257                        synchronized (mPackages) {
23258                            retCode = PackageManager.INSTALL_SUCCEEDED;
23259                            pkgList.add(pkg.packageName);
23260                            // Post process args
23261                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
23262                                    pkg.applicationInfo.uid);
23263                        }
23264                    } else {
23265                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
23266                    }
23267                }
23268
23269            } finally {
23270                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
23271                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
23272                }
23273            }
23274        }
23275        // writer
23276        synchronized (mPackages) {
23277            // If the platform SDK has changed since the last time we booted,
23278            // we need to re-grant app permission to catch any new ones that
23279            // appear. This is really a hack, and means that apps can in some
23280            // cases get permissions that the user didn't initially explicitly
23281            // allow... it would be nice to have some better way to handle
23282            // this situation.
23283            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
23284                    : mSettings.getInternalVersion();
23285            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
23286                    : StorageManager.UUID_PRIVATE_INTERNAL;
23287
23288            int updateFlags = UPDATE_PERMISSIONS_ALL;
23289            if (ver.sdkVersion != mSdkVersion) {
23290                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23291                        + mSdkVersion + "; regranting permissions for external");
23292                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23293            }
23294            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23295
23296            // Yay, everything is now upgraded
23297            ver.forceCurrent();
23298
23299            // can downgrade to reader
23300            // Persist settings
23301            mSettings.writeLPr();
23302        }
23303        // Send a broadcast to let everyone know we are done processing
23304        if (pkgList.size() > 0) {
23305            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
23306        }
23307    }
23308
23309   /*
23310     * Utility method to unload a list of specified containers
23311     */
23312    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
23313        // Just unmount all valid containers.
23314        for (AsecInstallArgs arg : cidArgs) {
23315            synchronized (mInstallLock) {
23316                arg.doPostDeleteLI(false);
23317           }
23318       }
23319   }
23320
23321    /*
23322     * Unload packages mounted on external media. This involves deleting package
23323     * data from internal structures, sending broadcasts about disabled packages,
23324     * gc'ing to free up references, unmounting all secure containers
23325     * corresponding to packages on external media, and posting a
23326     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
23327     * that we always have to post this message if status has been requested no
23328     * matter what.
23329     */
23330    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
23331            final boolean reportStatus) {
23332        if (DEBUG_SD_INSTALL)
23333            Log.i(TAG, "unloading media packages");
23334        ArrayList<String> pkgList = new ArrayList<String>();
23335        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
23336        final Set<AsecInstallArgs> keys = processCids.keySet();
23337        for (AsecInstallArgs args : keys) {
23338            String pkgName = args.getPackageName();
23339            if (DEBUG_SD_INSTALL)
23340                Log.i(TAG, "Trying to unload pkg : " + pkgName);
23341            // Delete package internally
23342            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23343            synchronized (mInstallLock) {
23344                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23345                final boolean res;
23346                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
23347                        "unloadMediaPackages")) {
23348                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
23349                            null);
23350                }
23351                if (res) {
23352                    pkgList.add(pkgName);
23353                } else {
23354                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
23355                    failedList.add(args);
23356                }
23357            }
23358        }
23359
23360        // reader
23361        synchronized (mPackages) {
23362            // We didn't update the settings after removing each package;
23363            // write them now for all packages.
23364            mSettings.writeLPr();
23365        }
23366
23367        // We have to absolutely send UPDATED_MEDIA_STATUS only
23368        // after confirming that all the receivers processed the ordered
23369        // broadcast when packages get disabled, force a gc to clean things up.
23370        // and unload all the containers.
23371        if (pkgList.size() > 0) {
23372            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
23373                    new IIntentReceiver.Stub() {
23374                public void performReceive(Intent intent, int resultCode, String data,
23375                        Bundle extras, boolean ordered, boolean sticky,
23376                        int sendingUser) throws RemoteException {
23377                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
23378                            reportStatus ? 1 : 0, 1, keys);
23379                    mHandler.sendMessage(msg);
23380                }
23381            });
23382        } else {
23383            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
23384                    keys);
23385            mHandler.sendMessage(msg);
23386        }
23387    }
23388
23389    private void loadPrivatePackages(final VolumeInfo vol) {
23390        mHandler.post(new Runnable() {
23391            @Override
23392            public void run() {
23393                loadPrivatePackagesInner(vol);
23394            }
23395        });
23396    }
23397
23398    private void loadPrivatePackagesInner(VolumeInfo vol) {
23399        final String volumeUuid = vol.fsUuid;
23400        if (TextUtils.isEmpty(volumeUuid)) {
23401            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23402            return;
23403        }
23404
23405        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23406        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23407        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23408
23409        final VersionInfo ver;
23410        final List<PackageSetting> packages;
23411        synchronized (mPackages) {
23412            ver = mSettings.findOrCreateVersion(volumeUuid);
23413            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23414        }
23415
23416        for (PackageSetting ps : packages) {
23417            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23418            synchronized (mInstallLock) {
23419                final PackageParser.Package pkg;
23420                try {
23421                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23422                    loaded.add(pkg.applicationInfo);
23423
23424                } catch (PackageManagerException e) {
23425                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23426                }
23427
23428                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23429                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23430                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23431                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23432                }
23433            }
23434        }
23435
23436        // Reconcile app data for all started/unlocked users
23437        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23438        final UserManager um = mContext.getSystemService(UserManager.class);
23439        UserManagerInternal umInternal = getUserManagerInternal();
23440        for (UserInfo user : um.getUsers()) {
23441            final int flags;
23442            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23443                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23444            } else if (umInternal.isUserRunning(user.id)) {
23445                flags = StorageManager.FLAG_STORAGE_DE;
23446            } else {
23447                continue;
23448            }
23449
23450            try {
23451                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23452                synchronized (mInstallLock) {
23453                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23454                }
23455            } catch (IllegalStateException e) {
23456                // Device was probably ejected, and we'll process that event momentarily
23457                Slog.w(TAG, "Failed to prepare storage: " + e);
23458            }
23459        }
23460
23461        synchronized (mPackages) {
23462            int updateFlags = UPDATE_PERMISSIONS_ALL;
23463            if (ver.sdkVersion != mSdkVersion) {
23464                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23465                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23466                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23467            }
23468            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23469
23470            // Yay, everything is now upgraded
23471            ver.forceCurrent();
23472
23473            mSettings.writeLPr();
23474        }
23475
23476        for (PackageFreezer freezer : freezers) {
23477            freezer.close();
23478        }
23479
23480        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23481        sendResourcesChangedBroadcast(true, false, loaded, null);
23482        mLoadedVolumes.add(vol.getId());
23483    }
23484
23485    private void unloadPrivatePackages(final VolumeInfo vol) {
23486        mHandler.post(new Runnable() {
23487            @Override
23488            public void run() {
23489                unloadPrivatePackagesInner(vol);
23490            }
23491        });
23492    }
23493
23494    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23495        final String volumeUuid = vol.fsUuid;
23496        if (TextUtils.isEmpty(volumeUuid)) {
23497            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23498            return;
23499        }
23500
23501        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23502        synchronized (mInstallLock) {
23503        synchronized (mPackages) {
23504            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23505            for (PackageSetting ps : packages) {
23506                if (ps.pkg == null) continue;
23507
23508                final ApplicationInfo info = ps.pkg.applicationInfo;
23509                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23510                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23511
23512                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23513                        "unloadPrivatePackagesInner")) {
23514                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23515                            false, null)) {
23516                        unloaded.add(info);
23517                    } else {
23518                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23519                    }
23520                }
23521
23522                // Try very hard to release any references to this package
23523                // so we don't risk the system server being killed due to
23524                // open FDs
23525                AttributeCache.instance().removePackage(ps.name);
23526            }
23527
23528            mSettings.writeLPr();
23529        }
23530        }
23531
23532        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23533        sendResourcesChangedBroadcast(false, false, unloaded, null);
23534        mLoadedVolumes.remove(vol.getId());
23535
23536        // Try very hard to release any references to this path so we don't risk
23537        // the system server being killed due to open FDs
23538        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23539
23540        for (int i = 0; i < 3; i++) {
23541            System.gc();
23542            System.runFinalization();
23543        }
23544    }
23545
23546    private void assertPackageKnown(String volumeUuid, String packageName)
23547            throws PackageManagerException {
23548        synchronized (mPackages) {
23549            // Normalize package name to handle renamed packages
23550            packageName = normalizePackageNameLPr(packageName);
23551
23552            final PackageSetting ps = mSettings.mPackages.get(packageName);
23553            if (ps == null) {
23554                throw new PackageManagerException("Package " + packageName + " is unknown");
23555            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23556                throw new PackageManagerException(
23557                        "Package " + packageName + " found on unknown volume " + volumeUuid
23558                                + "; expected volume " + ps.volumeUuid);
23559            }
23560        }
23561    }
23562
23563    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23564            throws PackageManagerException {
23565        synchronized (mPackages) {
23566            // Normalize package name to handle renamed packages
23567            packageName = normalizePackageNameLPr(packageName);
23568
23569            final PackageSetting ps = mSettings.mPackages.get(packageName);
23570            if (ps == null) {
23571                throw new PackageManagerException("Package " + packageName + " is unknown");
23572            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23573                throw new PackageManagerException(
23574                        "Package " + packageName + " found on unknown volume " + volumeUuid
23575                                + "; expected volume " + ps.volumeUuid);
23576            } else if (!ps.getInstalled(userId)) {
23577                throw new PackageManagerException(
23578                        "Package " + packageName + " not installed for user " + userId);
23579            }
23580        }
23581    }
23582
23583    private List<String> collectAbsoluteCodePaths() {
23584        synchronized (mPackages) {
23585            List<String> codePaths = new ArrayList<>();
23586            final int packageCount = mSettings.mPackages.size();
23587            for (int i = 0; i < packageCount; i++) {
23588                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23589                codePaths.add(ps.codePath.getAbsolutePath());
23590            }
23591            return codePaths;
23592        }
23593    }
23594
23595    /**
23596     * Examine all apps present on given mounted volume, and destroy apps that
23597     * aren't expected, either due to uninstallation or reinstallation on
23598     * another volume.
23599     */
23600    private void reconcileApps(String volumeUuid) {
23601        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23602        List<File> filesToDelete = null;
23603
23604        final File[] files = FileUtils.listFilesOrEmpty(
23605                Environment.getDataAppDirectory(volumeUuid));
23606        for (File file : files) {
23607            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23608                    && !PackageInstallerService.isStageName(file.getName());
23609            if (!isPackage) {
23610                // Ignore entries which are not packages
23611                continue;
23612            }
23613
23614            String absolutePath = file.getAbsolutePath();
23615
23616            boolean pathValid = false;
23617            final int absoluteCodePathCount = absoluteCodePaths.size();
23618            for (int i = 0; i < absoluteCodePathCount; i++) {
23619                String absoluteCodePath = absoluteCodePaths.get(i);
23620                if (absolutePath.startsWith(absoluteCodePath)) {
23621                    pathValid = true;
23622                    break;
23623                }
23624            }
23625
23626            if (!pathValid) {
23627                if (filesToDelete == null) {
23628                    filesToDelete = new ArrayList<>();
23629                }
23630                filesToDelete.add(file);
23631            }
23632        }
23633
23634        if (filesToDelete != null) {
23635            final int fileToDeleteCount = filesToDelete.size();
23636            for (int i = 0; i < fileToDeleteCount; i++) {
23637                File fileToDelete = filesToDelete.get(i);
23638                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23639                synchronized (mInstallLock) {
23640                    removeCodePathLI(fileToDelete);
23641                }
23642            }
23643        }
23644    }
23645
23646    /**
23647     * Reconcile all app data for the given user.
23648     * <p>
23649     * Verifies that directories exist and that ownership and labeling is
23650     * correct for all installed apps on all mounted volumes.
23651     */
23652    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23653        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23654        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23655            final String volumeUuid = vol.getFsUuid();
23656            synchronized (mInstallLock) {
23657                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23658            }
23659        }
23660    }
23661
23662    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23663            boolean migrateAppData) {
23664        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23665    }
23666
23667    /**
23668     * Reconcile all app data on given mounted volume.
23669     * <p>
23670     * Destroys app data that isn't expected, either due to uninstallation or
23671     * reinstallation on another volume.
23672     * <p>
23673     * Verifies that directories exist and that ownership and labeling is
23674     * correct for all installed apps.
23675     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23676     */
23677    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23678            boolean migrateAppData, boolean onlyCoreApps) {
23679        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23680                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23681        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23682
23683        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23684        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23685
23686        // First look for stale data that doesn't belong, and check if things
23687        // have changed since we did our last restorecon
23688        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23689            if (StorageManager.isFileEncryptedNativeOrEmulated()
23690                    && !StorageManager.isUserKeyUnlocked(userId)) {
23691                throw new RuntimeException(
23692                        "Yikes, someone asked us to reconcile CE storage while " + userId
23693                                + " was still locked; this would have caused massive data loss!");
23694            }
23695
23696            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23697            for (File file : files) {
23698                final String packageName = file.getName();
23699                try {
23700                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23701                } catch (PackageManagerException e) {
23702                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23703                    try {
23704                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23705                                StorageManager.FLAG_STORAGE_CE, 0);
23706                    } catch (InstallerException e2) {
23707                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23708                    }
23709                }
23710            }
23711        }
23712        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23713            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23714            for (File file : files) {
23715                final String packageName = file.getName();
23716                try {
23717                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23718                } catch (PackageManagerException e) {
23719                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23720                    try {
23721                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23722                                StorageManager.FLAG_STORAGE_DE, 0);
23723                    } catch (InstallerException e2) {
23724                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23725                    }
23726                }
23727            }
23728        }
23729
23730        // Ensure that data directories are ready to roll for all packages
23731        // installed for this volume and user
23732        final List<PackageSetting> packages;
23733        synchronized (mPackages) {
23734            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23735        }
23736        int preparedCount = 0;
23737        for (PackageSetting ps : packages) {
23738            final String packageName = ps.name;
23739            if (ps.pkg == null) {
23740                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23741                // TODO: might be due to legacy ASEC apps; we should circle back
23742                // and reconcile again once they're scanned
23743                continue;
23744            }
23745            // Skip non-core apps if requested
23746            if (onlyCoreApps && !ps.pkg.coreApp) {
23747                result.add(packageName);
23748                continue;
23749            }
23750
23751            if (ps.getInstalled(userId)) {
23752                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23753                preparedCount++;
23754            }
23755        }
23756
23757        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23758        return result;
23759    }
23760
23761    /**
23762     * Prepare app data for the given app just after it was installed or
23763     * upgraded. This method carefully only touches users that it's installed
23764     * for, and it forces a restorecon to handle any seinfo changes.
23765     * <p>
23766     * Verifies that directories exist and that ownership and labeling is
23767     * correct for all installed apps. If there is an ownership mismatch, it
23768     * will try recovering system apps by wiping data; third-party app data is
23769     * left intact.
23770     * <p>
23771     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23772     */
23773    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23774        final PackageSetting ps;
23775        synchronized (mPackages) {
23776            ps = mSettings.mPackages.get(pkg.packageName);
23777            mSettings.writeKernelMappingLPr(ps);
23778        }
23779
23780        final UserManager um = mContext.getSystemService(UserManager.class);
23781        UserManagerInternal umInternal = getUserManagerInternal();
23782        for (UserInfo user : um.getUsers()) {
23783            final int flags;
23784            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23785                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23786            } else if (umInternal.isUserRunning(user.id)) {
23787                flags = StorageManager.FLAG_STORAGE_DE;
23788            } else {
23789                continue;
23790            }
23791
23792            if (ps.getInstalled(user.id)) {
23793                // TODO: when user data is locked, mark that we're still dirty
23794                prepareAppDataLIF(pkg, user.id, flags);
23795            }
23796        }
23797    }
23798
23799    /**
23800     * Prepare app data for the given app.
23801     * <p>
23802     * Verifies that directories exist and that ownership and labeling is
23803     * correct for all installed apps. If there is an ownership mismatch, this
23804     * will try recovering system apps by wiping data; third-party app data is
23805     * left intact.
23806     */
23807    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23808        if (pkg == null) {
23809            Slog.wtf(TAG, "Package was null!", new Throwable());
23810            return;
23811        }
23812        prepareAppDataLeafLIF(pkg, userId, flags);
23813        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23814        for (int i = 0; i < childCount; i++) {
23815            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23816        }
23817    }
23818
23819    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23820            boolean maybeMigrateAppData) {
23821        prepareAppDataLIF(pkg, userId, flags);
23822
23823        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23824            // We may have just shuffled around app data directories, so
23825            // prepare them one more time
23826            prepareAppDataLIF(pkg, userId, flags);
23827        }
23828    }
23829
23830    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23831        if (DEBUG_APP_DATA) {
23832            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23833                    + Integer.toHexString(flags));
23834        }
23835
23836        final String volumeUuid = pkg.volumeUuid;
23837        final String packageName = pkg.packageName;
23838        final ApplicationInfo app = pkg.applicationInfo;
23839        final int appId = UserHandle.getAppId(app.uid);
23840
23841        Preconditions.checkNotNull(app.seInfo);
23842
23843        long ceDataInode = -1;
23844        try {
23845            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23846                    appId, app.seInfo, app.targetSdkVersion);
23847        } catch (InstallerException e) {
23848            if (app.isSystemApp()) {
23849                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23850                        + ", but trying to recover: " + e);
23851                destroyAppDataLeafLIF(pkg, userId, flags);
23852                try {
23853                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23854                            appId, app.seInfo, app.targetSdkVersion);
23855                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23856                } catch (InstallerException e2) {
23857                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23858                }
23859            } else {
23860                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23861            }
23862        }
23863
23864        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23865            // TODO: mark this structure as dirty so we persist it!
23866            synchronized (mPackages) {
23867                final PackageSetting ps = mSettings.mPackages.get(packageName);
23868                if (ps != null) {
23869                    ps.setCeDataInode(ceDataInode, userId);
23870                }
23871            }
23872        }
23873
23874        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23875    }
23876
23877    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23878        if (pkg == null) {
23879            Slog.wtf(TAG, "Package was null!", new Throwable());
23880            return;
23881        }
23882        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23883        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23884        for (int i = 0; i < childCount; i++) {
23885            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23886        }
23887    }
23888
23889    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23890        final String volumeUuid = pkg.volumeUuid;
23891        final String packageName = pkg.packageName;
23892        final ApplicationInfo app = pkg.applicationInfo;
23893
23894        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23895            // Create a native library symlink only if we have native libraries
23896            // and if the native libraries are 32 bit libraries. We do not provide
23897            // this symlink for 64 bit libraries.
23898            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23899                final String nativeLibPath = app.nativeLibraryDir;
23900                try {
23901                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23902                            nativeLibPath, userId);
23903                } catch (InstallerException e) {
23904                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23905                }
23906            }
23907        }
23908    }
23909
23910    /**
23911     * For system apps on non-FBE devices, this method migrates any existing
23912     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23913     * requested by the app.
23914     */
23915    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23916        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23917                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23918            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23919                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23920            try {
23921                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23922                        storageTarget);
23923            } catch (InstallerException e) {
23924                logCriticalInfo(Log.WARN,
23925                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23926            }
23927            return true;
23928        } else {
23929            return false;
23930        }
23931    }
23932
23933    public PackageFreezer freezePackage(String packageName, String killReason) {
23934        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23935    }
23936
23937    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23938        return new PackageFreezer(packageName, userId, killReason);
23939    }
23940
23941    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23942            String killReason) {
23943        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23944    }
23945
23946    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23947            String killReason) {
23948        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23949            return new PackageFreezer();
23950        } else {
23951            return freezePackage(packageName, userId, killReason);
23952        }
23953    }
23954
23955    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23956            String killReason) {
23957        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23958    }
23959
23960    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23961            String killReason) {
23962        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23963            return new PackageFreezer();
23964        } else {
23965            return freezePackage(packageName, userId, killReason);
23966        }
23967    }
23968
23969    /**
23970     * Class that freezes and kills the given package upon creation, and
23971     * unfreezes it upon closing. This is typically used when doing surgery on
23972     * app code/data to prevent the app from running while you're working.
23973     */
23974    private class PackageFreezer implements AutoCloseable {
23975        private final String mPackageName;
23976        private final PackageFreezer[] mChildren;
23977
23978        private final boolean mWeFroze;
23979
23980        private final AtomicBoolean mClosed = new AtomicBoolean();
23981        private final CloseGuard mCloseGuard = CloseGuard.get();
23982
23983        /**
23984         * Create and return a stub freezer that doesn't actually do anything,
23985         * typically used when someone requested
23986         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23987         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23988         */
23989        public PackageFreezer() {
23990            mPackageName = null;
23991            mChildren = null;
23992            mWeFroze = false;
23993            mCloseGuard.open("close");
23994        }
23995
23996        public PackageFreezer(String packageName, int userId, String killReason) {
23997            synchronized (mPackages) {
23998                mPackageName = packageName;
23999                mWeFroze = mFrozenPackages.add(mPackageName);
24000
24001                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
24002                if (ps != null) {
24003                    killApplication(ps.name, ps.appId, userId, killReason);
24004                }
24005
24006                final PackageParser.Package p = mPackages.get(packageName);
24007                if (p != null && p.childPackages != null) {
24008                    final int N = p.childPackages.size();
24009                    mChildren = new PackageFreezer[N];
24010                    for (int i = 0; i < N; i++) {
24011                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
24012                                userId, killReason);
24013                    }
24014                } else {
24015                    mChildren = null;
24016                }
24017            }
24018            mCloseGuard.open("close");
24019        }
24020
24021        @Override
24022        protected void finalize() throws Throwable {
24023            try {
24024                if (mCloseGuard != null) {
24025                    mCloseGuard.warnIfOpen();
24026                }
24027
24028                close();
24029            } finally {
24030                super.finalize();
24031            }
24032        }
24033
24034        @Override
24035        public void close() {
24036            mCloseGuard.close();
24037            if (mClosed.compareAndSet(false, true)) {
24038                synchronized (mPackages) {
24039                    if (mWeFroze) {
24040                        mFrozenPackages.remove(mPackageName);
24041                    }
24042
24043                    if (mChildren != null) {
24044                        for (PackageFreezer freezer : mChildren) {
24045                            freezer.close();
24046                        }
24047                    }
24048                }
24049            }
24050        }
24051    }
24052
24053    /**
24054     * Verify that given package is currently frozen.
24055     */
24056    private void checkPackageFrozen(String packageName) {
24057        synchronized (mPackages) {
24058            if (!mFrozenPackages.contains(packageName)) {
24059                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
24060            }
24061        }
24062    }
24063
24064    @Override
24065    public int movePackage(final String packageName, final String volumeUuid) {
24066        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24067
24068        final int callingUid = Binder.getCallingUid();
24069        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
24070        final int moveId = mNextMoveId.getAndIncrement();
24071        mHandler.post(new Runnable() {
24072            @Override
24073            public void run() {
24074                try {
24075                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
24076                } catch (PackageManagerException e) {
24077                    Slog.w(TAG, "Failed to move " + packageName, e);
24078                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
24079                }
24080            }
24081        });
24082        return moveId;
24083    }
24084
24085    private void movePackageInternal(final String packageName, final String volumeUuid,
24086            final int moveId, final int callingUid, UserHandle user)
24087                    throws PackageManagerException {
24088        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24089        final PackageManager pm = mContext.getPackageManager();
24090
24091        final boolean currentAsec;
24092        final String currentVolumeUuid;
24093        final File codeFile;
24094        final String installerPackageName;
24095        final String packageAbiOverride;
24096        final int appId;
24097        final String seinfo;
24098        final String label;
24099        final int targetSdkVersion;
24100        final PackageFreezer freezer;
24101        final int[] installedUserIds;
24102
24103        // reader
24104        synchronized (mPackages) {
24105            final PackageParser.Package pkg = mPackages.get(packageName);
24106            final PackageSetting ps = mSettings.mPackages.get(packageName);
24107            if (pkg == null
24108                    || ps == null
24109                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
24110                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
24111            }
24112            if (pkg.applicationInfo.isSystemApp()) {
24113                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
24114                        "Cannot move system application");
24115            }
24116
24117            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
24118            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
24119                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
24120            if (isInternalStorage && !allow3rdPartyOnInternal) {
24121                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
24122                        "3rd party apps are not allowed on internal storage");
24123            }
24124
24125            if (pkg.applicationInfo.isExternalAsec()) {
24126                currentAsec = true;
24127                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
24128            } else if (pkg.applicationInfo.isForwardLocked()) {
24129                currentAsec = true;
24130                currentVolumeUuid = "forward_locked";
24131            } else {
24132                currentAsec = false;
24133                currentVolumeUuid = ps.volumeUuid;
24134
24135                final File probe = new File(pkg.codePath);
24136                final File probeOat = new File(probe, "oat");
24137                if (!probe.isDirectory() || !probeOat.isDirectory()) {
24138                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24139                            "Move only supported for modern cluster style installs");
24140                }
24141            }
24142
24143            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
24144                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24145                        "Package already moved to " + volumeUuid);
24146            }
24147            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
24148                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
24149                        "Device admin cannot be moved");
24150            }
24151
24152            if (mFrozenPackages.contains(packageName)) {
24153                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
24154                        "Failed to move already frozen package");
24155            }
24156
24157            codeFile = new File(pkg.codePath);
24158            installerPackageName = ps.installerPackageName;
24159            packageAbiOverride = ps.cpuAbiOverrideString;
24160            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
24161            seinfo = pkg.applicationInfo.seInfo;
24162            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
24163            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
24164            freezer = freezePackage(packageName, "movePackageInternal");
24165            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
24166        }
24167
24168        final Bundle extras = new Bundle();
24169        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
24170        extras.putString(Intent.EXTRA_TITLE, label);
24171        mMoveCallbacks.notifyCreated(moveId, extras);
24172
24173        int installFlags;
24174        final boolean moveCompleteApp;
24175        final File measurePath;
24176
24177        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
24178            installFlags = INSTALL_INTERNAL;
24179            moveCompleteApp = !currentAsec;
24180            measurePath = Environment.getDataAppDirectory(volumeUuid);
24181        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
24182            installFlags = INSTALL_EXTERNAL;
24183            moveCompleteApp = false;
24184            measurePath = storage.getPrimaryPhysicalVolume().getPath();
24185        } else {
24186            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
24187            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
24188                    || !volume.isMountedWritable()) {
24189                freezer.close();
24190                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24191                        "Move location not mounted private volume");
24192            }
24193
24194            Preconditions.checkState(!currentAsec);
24195
24196            installFlags = INSTALL_INTERNAL;
24197            moveCompleteApp = true;
24198            measurePath = Environment.getDataAppDirectory(volumeUuid);
24199        }
24200
24201        // If we're moving app data around, we need all the users unlocked
24202        if (moveCompleteApp) {
24203            for (int userId : installedUserIds) {
24204                if (StorageManager.isFileEncryptedNativeOrEmulated()
24205                        && !StorageManager.isUserKeyUnlocked(userId)) {
24206                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
24207                            "User " + userId + " must be unlocked");
24208                }
24209            }
24210        }
24211
24212        final PackageStats stats = new PackageStats(null, -1);
24213        synchronized (mInstaller) {
24214            for (int userId : installedUserIds) {
24215                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
24216                    freezer.close();
24217                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24218                            "Failed to measure package size");
24219                }
24220            }
24221        }
24222
24223        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
24224                + stats.dataSize);
24225
24226        final long startFreeBytes = measurePath.getUsableSpace();
24227        final long sizeBytes;
24228        if (moveCompleteApp) {
24229            sizeBytes = stats.codeSize + stats.dataSize;
24230        } else {
24231            sizeBytes = stats.codeSize;
24232        }
24233
24234        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
24235            freezer.close();
24236            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24237                    "Not enough free space to move");
24238        }
24239
24240        mMoveCallbacks.notifyStatusChanged(moveId, 10);
24241
24242        final CountDownLatch installedLatch = new CountDownLatch(1);
24243        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
24244            @Override
24245            public void onUserActionRequired(Intent intent) throws RemoteException {
24246                throw new IllegalStateException();
24247            }
24248
24249            @Override
24250            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
24251                    Bundle extras) throws RemoteException {
24252                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
24253                        + PackageManager.installStatusToString(returnCode, msg));
24254
24255                installedLatch.countDown();
24256                freezer.close();
24257
24258                final int status = PackageManager.installStatusToPublicStatus(returnCode);
24259                switch (status) {
24260                    case PackageInstaller.STATUS_SUCCESS:
24261                        mMoveCallbacks.notifyStatusChanged(moveId,
24262                                PackageManager.MOVE_SUCCEEDED);
24263                        break;
24264                    case PackageInstaller.STATUS_FAILURE_STORAGE:
24265                        mMoveCallbacks.notifyStatusChanged(moveId,
24266                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
24267                        break;
24268                    default:
24269                        mMoveCallbacks.notifyStatusChanged(moveId,
24270                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
24271                        break;
24272                }
24273            }
24274        };
24275
24276        final MoveInfo move;
24277        if (moveCompleteApp) {
24278            // Kick off a thread to report progress estimates
24279            new Thread() {
24280                @Override
24281                public void run() {
24282                    while (true) {
24283                        try {
24284                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
24285                                break;
24286                            }
24287                        } catch (InterruptedException ignored) {
24288                        }
24289
24290                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
24291                        final int progress = 10 + (int) MathUtils.constrain(
24292                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
24293                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
24294                    }
24295                }
24296            }.start();
24297
24298            final String dataAppName = codeFile.getName();
24299            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
24300                    dataAppName, appId, seinfo, targetSdkVersion);
24301        } else {
24302            move = null;
24303        }
24304
24305        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
24306
24307        final Message msg = mHandler.obtainMessage(INIT_COPY);
24308        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
24309        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
24310                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
24311                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
24312                PackageManager.INSTALL_REASON_UNKNOWN);
24313        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
24314        msg.obj = params;
24315
24316        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
24317                System.identityHashCode(msg.obj));
24318        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
24319                System.identityHashCode(msg.obj));
24320
24321        mHandler.sendMessage(msg);
24322    }
24323
24324    @Override
24325    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
24326        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24327
24328        final int realMoveId = mNextMoveId.getAndIncrement();
24329        final Bundle extras = new Bundle();
24330        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
24331        mMoveCallbacks.notifyCreated(realMoveId, extras);
24332
24333        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
24334            @Override
24335            public void onCreated(int moveId, Bundle extras) {
24336                // Ignored
24337            }
24338
24339            @Override
24340            public void onStatusChanged(int moveId, int status, long estMillis) {
24341                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
24342            }
24343        };
24344
24345        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24346        storage.setPrimaryStorageUuid(volumeUuid, callback);
24347        return realMoveId;
24348    }
24349
24350    @Override
24351    public int getMoveStatus(int moveId) {
24352        mContext.enforceCallingOrSelfPermission(
24353                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24354        return mMoveCallbacks.mLastStatus.get(moveId);
24355    }
24356
24357    @Override
24358    public void registerMoveCallback(IPackageMoveObserver callback) {
24359        mContext.enforceCallingOrSelfPermission(
24360                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24361        mMoveCallbacks.register(callback);
24362    }
24363
24364    @Override
24365    public void unregisterMoveCallback(IPackageMoveObserver callback) {
24366        mContext.enforceCallingOrSelfPermission(
24367                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24368        mMoveCallbacks.unregister(callback);
24369    }
24370
24371    @Override
24372    public boolean setInstallLocation(int loc) {
24373        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
24374                null);
24375        if (getInstallLocation() == loc) {
24376            return true;
24377        }
24378        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
24379                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
24380            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
24381                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
24382            return true;
24383        }
24384        return false;
24385   }
24386
24387    @Override
24388    public int getInstallLocation() {
24389        // allow instant app access
24390        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
24391                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
24392                PackageHelper.APP_INSTALL_AUTO);
24393    }
24394
24395    /** Called by UserManagerService */
24396    void cleanUpUser(UserManagerService userManager, int userHandle) {
24397        synchronized (mPackages) {
24398            mDirtyUsers.remove(userHandle);
24399            mUserNeedsBadging.delete(userHandle);
24400            mSettings.removeUserLPw(userHandle);
24401            mPendingBroadcasts.remove(userHandle);
24402            mInstantAppRegistry.onUserRemovedLPw(userHandle);
24403            removeUnusedPackagesLPw(userManager, userHandle);
24404        }
24405    }
24406
24407    /**
24408     * We're removing userHandle and would like to remove any downloaded packages
24409     * that are no longer in use by any other user.
24410     * @param userHandle the user being removed
24411     */
24412    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24413        final boolean DEBUG_CLEAN_APKS = false;
24414        int [] users = userManager.getUserIds();
24415        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24416        while (psit.hasNext()) {
24417            PackageSetting ps = psit.next();
24418            if (ps.pkg == null) {
24419                continue;
24420            }
24421            final String packageName = ps.pkg.packageName;
24422            // Skip over if system app
24423            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24424                continue;
24425            }
24426            if (DEBUG_CLEAN_APKS) {
24427                Slog.i(TAG, "Checking package " + packageName);
24428            }
24429            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24430            if (keep) {
24431                if (DEBUG_CLEAN_APKS) {
24432                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24433                }
24434            } else {
24435                for (int i = 0; i < users.length; i++) {
24436                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24437                        keep = true;
24438                        if (DEBUG_CLEAN_APKS) {
24439                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24440                                    + users[i]);
24441                        }
24442                        break;
24443                    }
24444                }
24445            }
24446            if (!keep) {
24447                if (DEBUG_CLEAN_APKS) {
24448                    Slog.i(TAG, "  Removing package " + packageName);
24449                }
24450                mHandler.post(new Runnable() {
24451                    public void run() {
24452                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24453                                userHandle, 0);
24454                    } //end run
24455                });
24456            }
24457        }
24458    }
24459
24460    /** Called by UserManagerService */
24461    void createNewUser(int userId, String[] disallowedPackages) {
24462        synchronized (mInstallLock) {
24463            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24464        }
24465        synchronized (mPackages) {
24466            scheduleWritePackageRestrictionsLocked(userId);
24467            scheduleWritePackageListLocked(userId);
24468            applyFactoryDefaultBrowserLPw(userId);
24469            primeDomainVerificationsLPw(userId);
24470        }
24471    }
24472
24473    void onNewUserCreated(final int userId) {
24474        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24475        // If permission review for legacy apps is required, we represent
24476        // dagerous permissions for such apps as always granted runtime
24477        // permissions to keep per user flag state whether review is needed.
24478        // Hence, if a new user is added we have to propagate dangerous
24479        // permission grants for these legacy apps.
24480        if (mPermissionReviewRequired) {
24481            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24482                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24483        }
24484    }
24485
24486    @Override
24487    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24488        mContext.enforceCallingOrSelfPermission(
24489                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24490                "Only package verification agents can read the verifier device identity");
24491
24492        synchronized (mPackages) {
24493            return mSettings.getVerifierDeviceIdentityLPw();
24494        }
24495    }
24496
24497    @Override
24498    public void setPermissionEnforced(String permission, boolean enforced) {
24499        // TODO: Now that we no longer change GID for storage, this should to away.
24500        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24501                "setPermissionEnforced");
24502        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24503            synchronized (mPackages) {
24504                if (mSettings.mReadExternalStorageEnforced == null
24505                        || mSettings.mReadExternalStorageEnforced != enforced) {
24506                    mSettings.mReadExternalStorageEnforced = enforced;
24507                    mSettings.writeLPr();
24508                }
24509            }
24510            // kill any non-foreground processes so we restart them and
24511            // grant/revoke the GID.
24512            final IActivityManager am = ActivityManager.getService();
24513            if (am != null) {
24514                final long token = Binder.clearCallingIdentity();
24515                try {
24516                    am.killProcessesBelowForeground("setPermissionEnforcement");
24517                } catch (RemoteException e) {
24518                } finally {
24519                    Binder.restoreCallingIdentity(token);
24520                }
24521            }
24522        } else {
24523            throw new IllegalArgumentException("No selective enforcement for " + permission);
24524        }
24525    }
24526
24527    @Override
24528    @Deprecated
24529    public boolean isPermissionEnforced(String permission) {
24530        // allow instant applications
24531        return true;
24532    }
24533
24534    @Override
24535    public boolean isStorageLow() {
24536        // allow instant applications
24537        final long token = Binder.clearCallingIdentity();
24538        try {
24539            final DeviceStorageMonitorInternal
24540                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24541            if (dsm != null) {
24542                return dsm.isMemoryLow();
24543            } else {
24544                return false;
24545            }
24546        } finally {
24547            Binder.restoreCallingIdentity(token);
24548        }
24549    }
24550
24551    @Override
24552    public IPackageInstaller getPackageInstaller() {
24553        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24554            return null;
24555        }
24556        return mInstallerService;
24557    }
24558
24559    private boolean userNeedsBadging(int userId) {
24560        int index = mUserNeedsBadging.indexOfKey(userId);
24561        if (index < 0) {
24562            final UserInfo userInfo;
24563            final long token = Binder.clearCallingIdentity();
24564            try {
24565                userInfo = sUserManager.getUserInfo(userId);
24566            } finally {
24567                Binder.restoreCallingIdentity(token);
24568            }
24569            final boolean b;
24570            if (userInfo != null && userInfo.isManagedProfile()) {
24571                b = true;
24572            } else {
24573                b = false;
24574            }
24575            mUserNeedsBadging.put(userId, b);
24576            return b;
24577        }
24578        return mUserNeedsBadging.valueAt(index);
24579    }
24580
24581    @Override
24582    public KeySet getKeySetByAlias(String packageName, String alias) {
24583        if (packageName == null || alias == null) {
24584            return null;
24585        }
24586        synchronized(mPackages) {
24587            final PackageParser.Package pkg = mPackages.get(packageName);
24588            if (pkg == null) {
24589                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24590                throw new IllegalArgumentException("Unknown package: " + packageName);
24591            }
24592            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24593            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24594                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24595                throw new IllegalArgumentException("Unknown package: " + packageName);
24596            }
24597            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24598            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24599        }
24600    }
24601
24602    @Override
24603    public KeySet getSigningKeySet(String packageName) {
24604        if (packageName == null) {
24605            return null;
24606        }
24607        synchronized(mPackages) {
24608            final int callingUid = Binder.getCallingUid();
24609            final int callingUserId = UserHandle.getUserId(callingUid);
24610            final PackageParser.Package pkg = mPackages.get(packageName);
24611            if (pkg == null) {
24612                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24613                throw new IllegalArgumentException("Unknown package: " + packageName);
24614            }
24615            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24616            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24617                // filter and pretend the package doesn't exist
24618                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24619                        + ", uid:" + callingUid);
24620                throw new IllegalArgumentException("Unknown package: " + packageName);
24621            }
24622            if (pkg.applicationInfo.uid != callingUid
24623                    && Process.SYSTEM_UID != callingUid) {
24624                throw new SecurityException("May not access signing KeySet of other apps.");
24625            }
24626            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24627            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24628        }
24629    }
24630
24631    @Override
24632    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24633        final int callingUid = Binder.getCallingUid();
24634        if (getInstantAppPackageName(callingUid) != null) {
24635            return false;
24636        }
24637        if (packageName == null || ks == null) {
24638            return false;
24639        }
24640        synchronized(mPackages) {
24641            final PackageParser.Package pkg = mPackages.get(packageName);
24642            if (pkg == null
24643                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24644                            UserHandle.getUserId(callingUid))) {
24645                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24646                throw new IllegalArgumentException("Unknown package: " + packageName);
24647            }
24648            IBinder ksh = ks.getToken();
24649            if (ksh instanceof KeySetHandle) {
24650                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24651                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24652            }
24653            return false;
24654        }
24655    }
24656
24657    @Override
24658    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24659        final int callingUid = Binder.getCallingUid();
24660        if (getInstantAppPackageName(callingUid) != null) {
24661            return false;
24662        }
24663        if (packageName == null || ks == null) {
24664            return false;
24665        }
24666        synchronized(mPackages) {
24667            final PackageParser.Package pkg = mPackages.get(packageName);
24668            if (pkg == null
24669                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24670                            UserHandle.getUserId(callingUid))) {
24671                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24672                throw new IllegalArgumentException("Unknown package: " + packageName);
24673            }
24674            IBinder ksh = ks.getToken();
24675            if (ksh instanceof KeySetHandle) {
24676                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24677                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24678            }
24679            return false;
24680        }
24681    }
24682
24683    private void deletePackageIfUnusedLPr(final String packageName) {
24684        PackageSetting ps = mSettings.mPackages.get(packageName);
24685        if (ps == null) {
24686            return;
24687        }
24688        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24689            // TODO Implement atomic delete if package is unused
24690            // It is currently possible that the package will be deleted even if it is installed
24691            // after this method returns.
24692            mHandler.post(new Runnable() {
24693                public void run() {
24694                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24695                            0, PackageManager.DELETE_ALL_USERS);
24696                }
24697            });
24698        }
24699    }
24700
24701    /**
24702     * Check and throw if the given before/after packages would be considered a
24703     * downgrade.
24704     */
24705    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24706            throws PackageManagerException {
24707        if (after.versionCode < before.mVersionCode) {
24708            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24709                    "Update version code " + after.versionCode + " is older than current "
24710                    + before.mVersionCode);
24711        } else if (after.versionCode == before.mVersionCode) {
24712            if (after.baseRevisionCode < before.baseRevisionCode) {
24713                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24714                        "Update base revision code " + after.baseRevisionCode
24715                        + " is older than current " + before.baseRevisionCode);
24716            }
24717
24718            if (!ArrayUtils.isEmpty(after.splitNames)) {
24719                for (int i = 0; i < after.splitNames.length; i++) {
24720                    final String splitName = after.splitNames[i];
24721                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24722                    if (j != -1) {
24723                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24724                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24725                                    "Update split " + splitName + " revision code "
24726                                    + after.splitRevisionCodes[i] + " is older than current "
24727                                    + before.splitRevisionCodes[j]);
24728                        }
24729                    }
24730                }
24731            }
24732        }
24733    }
24734
24735    private static class MoveCallbacks extends Handler {
24736        private static final int MSG_CREATED = 1;
24737        private static final int MSG_STATUS_CHANGED = 2;
24738
24739        private final RemoteCallbackList<IPackageMoveObserver>
24740                mCallbacks = new RemoteCallbackList<>();
24741
24742        private final SparseIntArray mLastStatus = new SparseIntArray();
24743
24744        public MoveCallbacks(Looper looper) {
24745            super(looper);
24746        }
24747
24748        public void register(IPackageMoveObserver callback) {
24749            mCallbacks.register(callback);
24750        }
24751
24752        public void unregister(IPackageMoveObserver callback) {
24753            mCallbacks.unregister(callback);
24754        }
24755
24756        @Override
24757        public void handleMessage(Message msg) {
24758            final SomeArgs args = (SomeArgs) msg.obj;
24759            final int n = mCallbacks.beginBroadcast();
24760            for (int i = 0; i < n; i++) {
24761                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24762                try {
24763                    invokeCallback(callback, msg.what, args);
24764                } catch (RemoteException ignored) {
24765                }
24766            }
24767            mCallbacks.finishBroadcast();
24768            args.recycle();
24769        }
24770
24771        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24772                throws RemoteException {
24773            switch (what) {
24774                case MSG_CREATED: {
24775                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24776                    break;
24777                }
24778                case MSG_STATUS_CHANGED: {
24779                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24780                    break;
24781                }
24782            }
24783        }
24784
24785        private void notifyCreated(int moveId, Bundle extras) {
24786            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24787
24788            final SomeArgs args = SomeArgs.obtain();
24789            args.argi1 = moveId;
24790            args.arg2 = extras;
24791            obtainMessage(MSG_CREATED, args).sendToTarget();
24792        }
24793
24794        private void notifyStatusChanged(int moveId, int status) {
24795            notifyStatusChanged(moveId, status, -1);
24796        }
24797
24798        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24799            Slog.v(TAG, "Move " + moveId + " status " + status);
24800
24801            final SomeArgs args = SomeArgs.obtain();
24802            args.argi1 = moveId;
24803            args.argi2 = status;
24804            args.arg3 = estMillis;
24805            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24806
24807            synchronized (mLastStatus) {
24808                mLastStatus.put(moveId, status);
24809            }
24810        }
24811    }
24812
24813    private final static class OnPermissionChangeListeners extends Handler {
24814        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24815
24816        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24817                new RemoteCallbackList<>();
24818
24819        public OnPermissionChangeListeners(Looper looper) {
24820            super(looper);
24821        }
24822
24823        @Override
24824        public void handleMessage(Message msg) {
24825            switch (msg.what) {
24826                case MSG_ON_PERMISSIONS_CHANGED: {
24827                    final int uid = msg.arg1;
24828                    handleOnPermissionsChanged(uid);
24829                } break;
24830            }
24831        }
24832
24833        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24834            mPermissionListeners.register(listener);
24835
24836        }
24837
24838        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24839            mPermissionListeners.unregister(listener);
24840        }
24841
24842        public void onPermissionsChanged(int uid) {
24843            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24844                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24845            }
24846        }
24847
24848        private void handleOnPermissionsChanged(int uid) {
24849            final int count = mPermissionListeners.beginBroadcast();
24850            try {
24851                for (int i = 0; i < count; i++) {
24852                    IOnPermissionsChangeListener callback = mPermissionListeners
24853                            .getBroadcastItem(i);
24854                    try {
24855                        callback.onPermissionsChanged(uid);
24856                    } catch (RemoteException e) {
24857                        Log.e(TAG, "Permission listener is dead", e);
24858                    }
24859                }
24860            } finally {
24861                mPermissionListeners.finishBroadcast();
24862            }
24863        }
24864    }
24865
24866    private class PackageManagerNative extends IPackageManagerNative.Stub {
24867        @Override
24868        public String[] getNamesForUids(int[] uids) throws RemoteException {
24869            final String[] results = PackageManagerService.this.getNamesForUids(uids);
24870            // massage results so they can be parsed by the native binder
24871            for (int i = results.length - 1; i >= 0; --i) {
24872                if (results[i] == null) {
24873                    results[i] = "";
24874                }
24875            }
24876            return results;
24877        }
24878    }
24879
24880    private class PackageManagerInternalImpl extends PackageManagerInternal {
24881        @Override
24882        public void setLocationPackagesProvider(PackagesProvider provider) {
24883            synchronized (mPackages) {
24884                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24885            }
24886        }
24887
24888        @Override
24889        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24890            synchronized (mPackages) {
24891                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24892            }
24893        }
24894
24895        @Override
24896        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24897            synchronized (mPackages) {
24898                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24899            }
24900        }
24901
24902        @Override
24903        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24904            synchronized (mPackages) {
24905                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24906            }
24907        }
24908
24909        @Override
24910        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24911            synchronized (mPackages) {
24912                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24913            }
24914        }
24915
24916        @Override
24917        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24918            synchronized (mPackages) {
24919                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24920            }
24921        }
24922
24923        @Override
24924        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24925            synchronized (mPackages) {
24926                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24927                        packageName, userId);
24928            }
24929        }
24930
24931        @Override
24932        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24933            synchronized (mPackages) {
24934                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24935                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24936                        packageName, userId);
24937            }
24938        }
24939
24940        @Override
24941        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24942            synchronized (mPackages) {
24943                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24944                        packageName, userId);
24945            }
24946        }
24947
24948        @Override
24949        public void setKeepUninstalledPackages(final List<String> packageList) {
24950            Preconditions.checkNotNull(packageList);
24951            List<String> removedFromList = null;
24952            synchronized (mPackages) {
24953                if (mKeepUninstalledPackages != null) {
24954                    final int packagesCount = mKeepUninstalledPackages.size();
24955                    for (int i = 0; i < packagesCount; i++) {
24956                        String oldPackage = mKeepUninstalledPackages.get(i);
24957                        if (packageList != null && packageList.contains(oldPackage)) {
24958                            continue;
24959                        }
24960                        if (removedFromList == null) {
24961                            removedFromList = new ArrayList<>();
24962                        }
24963                        removedFromList.add(oldPackage);
24964                    }
24965                }
24966                mKeepUninstalledPackages = new ArrayList<>(packageList);
24967                if (removedFromList != null) {
24968                    final int removedCount = removedFromList.size();
24969                    for (int i = 0; i < removedCount; i++) {
24970                        deletePackageIfUnusedLPr(removedFromList.get(i));
24971                    }
24972                }
24973            }
24974        }
24975
24976        @Override
24977        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24978            synchronized (mPackages) {
24979                // If we do not support permission review, done.
24980                if (!mPermissionReviewRequired) {
24981                    return false;
24982                }
24983
24984                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24985                if (packageSetting == null) {
24986                    return false;
24987                }
24988
24989                // Permission review applies only to apps not supporting the new permission model.
24990                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24991                    return false;
24992                }
24993
24994                // Legacy apps have the permission and get user consent on launch.
24995                PermissionsState permissionsState = packageSetting.getPermissionsState();
24996                return permissionsState.isPermissionReviewRequired(userId);
24997            }
24998        }
24999
25000        @Override
25001        public PackageInfo getPackageInfo(
25002                String packageName, int flags, int filterCallingUid, int userId) {
25003            return PackageManagerService.this
25004                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
25005                            flags, filterCallingUid, userId);
25006        }
25007
25008        @Override
25009        public ApplicationInfo getApplicationInfo(
25010                String packageName, int flags, int filterCallingUid, int userId) {
25011            return PackageManagerService.this
25012                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
25013        }
25014
25015        @Override
25016        public ActivityInfo getActivityInfo(
25017                ComponentName component, int flags, int filterCallingUid, int userId) {
25018            return PackageManagerService.this
25019                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
25020        }
25021
25022        @Override
25023        public List<ResolveInfo> queryIntentActivities(
25024                Intent intent, int flags, int filterCallingUid, int userId) {
25025            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
25026            return PackageManagerService.this
25027                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
25028                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
25029        }
25030
25031        @Override
25032        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
25033                int userId) {
25034            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
25035        }
25036
25037        @Override
25038        public void setDeviceAndProfileOwnerPackages(
25039                int deviceOwnerUserId, String deviceOwnerPackage,
25040                SparseArray<String> profileOwnerPackages) {
25041            mProtectedPackages.setDeviceAndProfileOwnerPackages(
25042                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
25043        }
25044
25045        @Override
25046        public boolean isPackageDataProtected(int userId, String packageName) {
25047            return mProtectedPackages.isPackageDataProtected(userId, packageName);
25048        }
25049
25050        @Override
25051        public boolean isPackageEphemeral(int userId, String packageName) {
25052            synchronized (mPackages) {
25053                final PackageSetting ps = mSettings.mPackages.get(packageName);
25054                return ps != null ? ps.getInstantApp(userId) : false;
25055            }
25056        }
25057
25058        @Override
25059        public boolean wasPackageEverLaunched(String packageName, int userId) {
25060            synchronized (mPackages) {
25061                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
25062            }
25063        }
25064
25065        @Override
25066        public void grantRuntimePermission(String packageName, String name, int userId,
25067                boolean overridePolicy) {
25068            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
25069                    overridePolicy);
25070        }
25071
25072        @Override
25073        public void revokeRuntimePermission(String packageName, String name, int userId,
25074                boolean overridePolicy) {
25075            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
25076                    overridePolicy);
25077        }
25078
25079        @Override
25080        public String getNameForUid(int uid) {
25081            return PackageManagerService.this.getNameForUid(uid);
25082        }
25083
25084        @Override
25085        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
25086                Intent origIntent, String resolvedType, String callingPackage,
25087                Bundle verificationBundle, int userId) {
25088            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
25089                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
25090                    userId);
25091        }
25092
25093        @Override
25094        public void grantEphemeralAccess(int userId, Intent intent,
25095                int targetAppId, int ephemeralAppId) {
25096            synchronized (mPackages) {
25097                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
25098                        targetAppId, ephemeralAppId);
25099            }
25100        }
25101
25102        @Override
25103        public boolean isInstantAppInstallerComponent(ComponentName component) {
25104            synchronized (mPackages) {
25105                return mInstantAppInstallerActivity != null
25106                        && mInstantAppInstallerActivity.getComponentName().equals(component);
25107            }
25108        }
25109
25110        @Override
25111        public void pruneInstantApps() {
25112            mInstantAppRegistry.pruneInstantApps();
25113        }
25114
25115        @Override
25116        public String getSetupWizardPackageName() {
25117            return mSetupWizardPackage;
25118        }
25119
25120        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
25121            if (policy != null) {
25122                mExternalSourcesPolicy = policy;
25123            }
25124        }
25125
25126        @Override
25127        public boolean isPackagePersistent(String packageName) {
25128            synchronized (mPackages) {
25129                PackageParser.Package pkg = mPackages.get(packageName);
25130                return pkg != null
25131                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
25132                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
25133                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
25134                        : false;
25135            }
25136        }
25137
25138        @Override
25139        public List<PackageInfo> getOverlayPackages(int userId) {
25140            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
25141            synchronized (mPackages) {
25142                for (PackageParser.Package p : mPackages.values()) {
25143                    if (p.mOverlayTarget != null) {
25144                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
25145                        if (pkg != null) {
25146                            overlayPackages.add(pkg);
25147                        }
25148                    }
25149                }
25150            }
25151            return overlayPackages;
25152        }
25153
25154        @Override
25155        public List<String> getTargetPackageNames(int userId) {
25156            List<String> targetPackages = new ArrayList<>();
25157            synchronized (mPackages) {
25158                for (PackageParser.Package p : mPackages.values()) {
25159                    if (p.mOverlayTarget == null) {
25160                        targetPackages.add(p.packageName);
25161                    }
25162                }
25163            }
25164            return targetPackages;
25165        }
25166
25167        @Override
25168        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
25169                @Nullable List<String> overlayPackageNames) {
25170            synchronized (mPackages) {
25171                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
25172                    Slog.e(TAG, "failed to find package " + targetPackageName);
25173                    return false;
25174                }
25175                ArrayList<String> overlayPaths = null;
25176                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
25177                    final int N = overlayPackageNames.size();
25178                    overlayPaths = new ArrayList<>(N);
25179                    for (int i = 0; i < N; i++) {
25180                        final String packageName = overlayPackageNames.get(i);
25181                        final PackageParser.Package pkg = mPackages.get(packageName);
25182                        if (pkg == null) {
25183                            Slog.e(TAG, "failed to find package " + packageName);
25184                            return false;
25185                        }
25186                        overlayPaths.add(pkg.baseCodePath);
25187                    }
25188                }
25189
25190                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
25191                ps.setOverlayPaths(overlayPaths, userId);
25192                return true;
25193            }
25194        }
25195
25196        @Override
25197        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
25198                int flags, int userId) {
25199            return resolveIntentInternal(
25200                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
25201        }
25202
25203        @Override
25204        public ResolveInfo resolveService(Intent intent, String resolvedType,
25205                int flags, int userId, int callingUid) {
25206            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
25207        }
25208
25209        @Override
25210        public void addIsolatedUid(int isolatedUid, int ownerUid) {
25211            synchronized (mPackages) {
25212                mIsolatedOwners.put(isolatedUid, ownerUid);
25213            }
25214        }
25215
25216        @Override
25217        public void removeIsolatedUid(int isolatedUid) {
25218            synchronized (mPackages) {
25219                mIsolatedOwners.delete(isolatedUid);
25220            }
25221        }
25222
25223        @Override
25224        public int getUidTargetSdkVersion(int uid) {
25225            synchronized (mPackages) {
25226                return getUidTargetSdkVersionLockedLPr(uid);
25227            }
25228        }
25229
25230        @Override
25231        public boolean canAccessInstantApps(int callingUid, int userId) {
25232            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
25233        }
25234    }
25235
25236    @Override
25237    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
25238        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
25239        synchronized (mPackages) {
25240            final long identity = Binder.clearCallingIdentity();
25241            try {
25242                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
25243                        packageNames, userId);
25244            } finally {
25245                Binder.restoreCallingIdentity(identity);
25246            }
25247        }
25248    }
25249
25250    @Override
25251    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
25252        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
25253        synchronized (mPackages) {
25254            final long identity = Binder.clearCallingIdentity();
25255            try {
25256                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
25257                        packageNames, userId);
25258            } finally {
25259                Binder.restoreCallingIdentity(identity);
25260            }
25261        }
25262    }
25263
25264    private static void enforceSystemOrPhoneCaller(String tag) {
25265        int callingUid = Binder.getCallingUid();
25266        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
25267            throw new SecurityException(
25268                    "Cannot call " + tag + " from UID " + callingUid);
25269        }
25270    }
25271
25272    boolean isHistoricalPackageUsageAvailable() {
25273        return mPackageUsage.isHistoricalPackageUsageAvailable();
25274    }
25275
25276    /**
25277     * Return a <b>copy</b> of the collection of packages known to the package manager.
25278     * @return A copy of the values of mPackages.
25279     */
25280    Collection<PackageParser.Package> getPackages() {
25281        synchronized (mPackages) {
25282            return new ArrayList<>(mPackages.values());
25283        }
25284    }
25285
25286    /**
25287     * Logs process start information (including base APK hash) to the security log.
25288     * @hide
25289     */
25290    @Override
25291    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
25292            String apkFile, int pid) {
25293        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25294            return;
25295        }
25296        if (!SecurityLog.isLoggingEnabled()) {
25297            return;
25298        }
25299        Bundle data = new Bundle();
25300        data.putLong("startTimestamp", System.currentTimeMillis());
25301        data.putString("processName", processName);
25302        data.putInt("uid", uid);
25303        data.putString("seinfo", seinfo);
25304        data.putString("apkFile", apkFile);
25305        data.putInt("pid", pid);
25306        Message msg = mProcessLoggingHandler.obtainMessage(
25307                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
25308        msg.setData(data);
25309        mProcessLoggingHandler.sendMessage(msg);
25310    }
25311
25312    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
25313        return mCompilerStats.getPackageStats(pkgName);
25314    }
25315
25316    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
25317        return getOrCreateCompilerPackageStats(pkg.packageName);
25318    }
25319
25320    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
25321        return mCompilerStats.getOrCreatePackageStats(pkgName);
25322    }
25323
25324    public void deleteCompilerPackageStats(String pkgName) {
25325        mCompilerStats.deletePackageStats(pkgName);
25326    }
25327
25328    @Override
25329    public int getInstallReason(String packageName, int userId) {
25330        final int callingUid = Binder.getCallingUid();
25331        enforceCrossUserPermission(callingUid, userId,
25332                true /* requireFullPermission */, false /* checkShell */,
25333                "get install reason");
25334        synchronized (mPackages) {
25335            final PackageSetting ps = mSettings.mPackages.get(packageName);
25336            if (filterAppAccessLPr(ps, callingUid, userId)) {
25337                return PackageManager.INSTALL_REASON_UNKNOWN;
25338            }
25339            if (ps != null) {
25340                return ps.getInstallReason(userId);
25341            }
25342        }
25343        return PackageManager.INSTALL_REASON_UNKNOWN;
25344    }
25345
25346    @Override
25347    public boolean canRequestPackageInstalls(String packageName, int userId) {
25348        return canRequestPackageInstallsInternal(packageName, 0, userId,
25349                true /* throwIfPermNotDeclared*/);
25350    }
25351
25352    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
25353            boolean throwIfPermNotDeclared) {
25354        int callingUid = Binder.getCallingUid();
25355        int uid = getPackageUid(packageName, 0, userId);
25356        if (callingUid != uid && callingUid != Process.ROOT_UID
25357                && callingUid != Process.SYSTEM_UID) {
25358            throw new SecurityException(
25359                    "Caller uid " + callingUid + " does not own package " + packageName);
25360        }
25361        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
25362        if (info == null) {
25363            return false;
25364        }
25365        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
25366            return false;
25367        }
25368        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
25369        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
25370        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
25371            if (throwIfPermNotDeclared) {
25372                throw new SecurityException("Need to declare " + appOpPermission
25373                        + " to call this api");
25374            } else {
25375                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
25376                return false;
25377            }
25378        }
25379        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
25380            return false;
25381        }
25382        if (mExternalSourcesPolicy != null) {
25383            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
25384            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
25385                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
25386            }
25387        }
25388        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
25389    }
25390
25391    @Override
25392    public ComponentName getInstantAppResolverSettingsComponent() {
25393        return mInstantAppResolverSettingsComponent;
25394    }
25395
25396    @Override
25397    public ComponentName getInstantAppInstallerComponent() {
25398        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25399            return null;
25400        }
25401        return mInstantAppInstallerActivity == null
25402                ? null : mInstantAppInstallerActivity.getComponentName();
25403    }
25404
25405    @Override
25406    public String getInstantAppAndroidId(String packageName, int userId) {
25407        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25408                "getInstantAppAndroidId");
25409        enforceCrossUserPermission(Binder.getCallingUid(), userId,
25410                true /* requireFullPermission */, false /* checkShell */,
25411                "getInstantAppAndroidId");
25412        // Make sure the target is an Instant App.
25413        if (!isInstantApp(packageName, userId)) {
25414            return null;
25415        }
25416        synchronized (mPackages) {
25417            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25418        }
25419    }
25420
25421    boolean canHaveOatDir(String packageName) {
25422        synchronized (mPackages) {
25423            PackageParser.Package p = mPackages.get(packageName);
25424            if (p == null) {
25425                return false;
25426            }
25427            return p.canHaveOatDir();
25428        }
25429    }
25430
25431    private String getOatDir(PackageParser.Package pkg) {
25432        if (!pkg.canHaveOatDir()) {
25433            return null;
25434        }
25435        File codePath = new File(pkg.codePath);
25436        if (codePath.isDirectory()) {
25437            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25438        }
25439        return null;
25440    }
25441
25442    void deleteOatArtifactsOfPackage(String packageName) {
25443        final String[] instructionSets;
25444        final List<String> codePaths;
25445        final String oatDir;
25446        final PackageParser.Package pkg;
25447        synchronized (mPackages) {
25448            pkg = mPackages.get(packageName);
25449        }
25450        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25451        codePaths = pkg.getAllCodePaths();
25452        oatDir = getOatDir(pkg);
25453
25454        for (String codePath : codePaths) {
25455            for (String isa : instructionSets) {
25456                try {
25457                    mInstaller.deleteOdex(codePath, isa, oatDir);
25458                } catch (InstallerException e) {
25459                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25460                }
25461            }
25462        }
25463    }
25464
25465    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25466        Set<String> unusedPackages = new HashSet<>();
25467        long currentTimeInMillis = System.currentTimeMillis();
25468        synchronized (mPackages) {
25469            for (PackageParser.Package pkg : mPackages.values()) {
25470                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25471                if (ps == null) {
25472                    continue;
25473                }
25474                PackageDexUsage.PackageUseInfo packageUseInfo =
25475                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
25476                if (PackageManagerServiceUtils
25477                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25478                                downgradeTimeThresholdMillis, packageUseInfo,
25479                                pkg.getLatestPackageUseTimeInMills(),
25480                                pkg.getLatestForegroundPackageUseTimeInMills())) {
25481                    unusedPackages.add(pkg.packageName);
25482                }
25483            }
25484        }
25485        return unusedPackages;
25486    }
25487}
25488
25489interface PackageSender {
25490    void sendPackageBroadcast(final String action, final String pkg,
25491        final Bundle extras, final int flags, final String targetPkg,
25492        final IIntentReceiver finishedReceiver, final int[] userIds);
25493    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
25494        boolean includeStopped, int appId, int... userIds);
25495}
25496