PackageManagerService.java revision 41a57a65b2a4fb51faa55bcba57ebe544e9f799f
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    /** Should not be with the scan flags */
453    static final int FLAGS_REMOVE_CHATTY = 1<<31;
454
455    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
456    /** Extension of the compressed packages */
457    private final static String COMPRESSED_EXTENSION = ".gz";
458
459    private static final int[] EMPTY_INT_ARRAY = new int[0];
460
461    private static final int TYPE_UNKNOWN = 0;
462    private static final int TYPE_ACTIVITY = 1;
463    private static final int TYPE_RECEIVER = 2;
464    private static final int TYPE_SERVICE = 3;
465    private static final int TYPE_PROVIDER = 4;
466    @IntDef(prefix = { "TYPE_" }, value = {
467            TYPE_UNKNOWN,
468            TYPE_ACTIVITY,
469            TYPE_RECEIVER,
470            TYPE_SERVICE,
471            TYPE_PROVIDER,
472    })
473    @Retention(RetentionPolicy.SOURCE)
474    public @interface ComponentType {}
475
476    /**
477     * Timeout (in milliseconds) after which the watchdog should declare that
478     * our handler thread is wedged.  The usual default for such things is one
479     * minute but we sometimes do very lengthy I/O operations on this thread,
480     * such as installing multi-gigabyte applications, so ours needs to be longer.
481     */
482    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
483
484    /**
485     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
486     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
487     * settings entry if available, otherwise we use the hardcoded default.  If it's been
488     * more than this long since the last fstrim, we force one during the boot sequence.
489     *
490     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
491     * one gets run at the next available charging+idle time.  This final mandatory
492     * no-fstrim check kicks in only of the other scheduling criteria is never met.
493     */
494    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
495
496    /**
497     * Whether verification is enabled by default.
498     */
499    private static final boolean DEFAULT_VERIFY_ENABLE = true;
500
501    /**
502     * The default maximum time to wait for the verification agent to return in
503     * milliseconds.
504     */
505    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
506
507    /**
508     * The default response for package verification timeout.
509     *
510     * This can be either PackageManager.VERIFICATION_ALLOW or
511     * PackageManager.VERIFICATION_REJECT.
512     */
513    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
514
515    static final String PLATFORM_PACKAGE_NAME = "android";
516
517    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
518
519    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
520            DEFAULT_CONTAINER_PACKAGE,
521            "com.android.defcontainer.DefaultContainerService");
522
523    private static final String KILL_APP_REASON_GIDS_CHANGED =
524            "permission grant or revoke changed gids";
525
526    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
527            "permissions revoked";
528
529    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
530
531    private static final String PACKAGE_SCHEME = "package";
532
533    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
534
535    /** Permission grant: not grant the permission. */
536    private static final int GRANT_DENIED = 1;
537
538    /** Permission grant: grant the permission as an install permission. */
539    private static final int GRANT_INSTALL = 2;
540
541    /** Permission grant: grant the permission as a runtime one. */
542    private static final int GRANT_RUNTIME = 3;
543
544    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
545    private static final int GRANT_UPGRADE = 4;
546
547    /** Canonical intent used to identify what counts as a "web browser" app */
548    private static final Intent sBrowserIntent;
549    static {
550        sBrowserIntent = new Intent();
551        sBrowserIntent.setAction(Intent.ACTION_VIEW);
552        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
553        sBrowserIntent.setData(Uri.parse("http:"));
554    }
555
556    /**
557     * The set of all protected actions [i.e. those actions for which a high priority
558     * intent filter is disallowed].
559     */
560    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
561    static {
562        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
563        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
564        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
565        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
566    }
567
568    // Compilation reasons.
569    public static final int REASON_FIRST_BOOT = 0;
570    public static final int REASON_BOOT = 1;
571    public static final int REASON_INSTALL = 2;
572    public static final int REASON_BACKGROUND_DEXOPT = 3;
573    public static final int REASON_AB_OTA = 4;
574    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
575
576    public static final int REASON_LAST = REASON_INACTIVE_PACKAGE_DOWNGRADE;
577
578    /** All dangerous permission names in the same order as the events in MetricsEvent */
579    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
580            Manifest.permission.READ_CALENDAR,
581            Manifest.permission.WRITE_CALENDAR,
582            Manifest.permission.CAMERA,
583            Manifest.permission.READ_CONTACTS,
584            Manifest.permission.WRITE_CONTACTS,
585            Manifest.permission.GET_ACCOUNTS,
586            Manifest.permission.ACCESS_FINE_LOCATION,
587            Manifest.permission.ACCESS_COARSE_LOCATION,
588            Manifest.permission.RECORD_AUDIO,
589            Manifest.permission.READ_PHONE_STATE,
590            Manifest.permission.CALL_PHONE,
591            Manifest.permission.READ_CALL_LOG,
592            Manifest.permission.WRITE_CALL_LOG,
593            Manifest.permission.ADD_VOICEMAIL,
594            Manifest.permission.USE_SIP,
595            Manifest.permission.PROCESS_OUTGOING_CALLS,
596            Manifest.permission.READ_CELL_BROADCASTS,
597            Manifest.permission.BODY_SENSORS,
598            Manifest.permission.SEND_SMS,
599            Manifest.permission.RECEIVE_SMS,
600            Manifest.permission.READ_SMS,
601            Manifest.permission.RECEIVE_WAP_PUSH,
602            Manifest.permission.RECEIVE_MMS,
603            Manifest.permission.READ_EXTERNAL_STORAGE,
604            Manifest.permission.WRITE_EXTERNAL_STORAGE,
605            Manifest.permission.READ_PHONE_NUMBERS,
606            Manifest.permission.ANSWER_PHONE_CALLS);
607
608
609    /**
610     * Version number for the package parser cache. Increment this whenever the format or
611     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
612     */
613    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
614
615    /**
616     * Whether the package parser cache is enabled.
617     */
618    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
619
620    final ServiceThread mHandlerThread;
621
622    final PackageHandler mHandler;
623
624    private final ProcessLoggingHandler mProcessLoggingHandler;
625
626    /**
627     * Messages for {@link #mHandler} that need to wait for system ready before
628     * being dispatched.
629     */
630    private ArrayList<Message> mPostSystemReadyMessages;
631
632    final int mSdkVersion = Build.VERSION.SDK_INT;
633
634    final Context mContext;
635    final boolean mFactoryTest;
636    final boolean mOnlyCore;
637    final DisplayMetrics mMetrics;
638    final int mDefParseFlags;
639    final String[] mSeparateProcesses;
640    final boolean mIsUpgrade;
641    final boolean mIsPreNUpgrade;
642    final boolean mIsPreNMR1Upgrade;
643
644    // Have we told the Activity Manager to whitelist the default container service by uid yet?
645    @GuardedBy("mPackages")
646    boolean mDefaultContainerWhitelisted = false;
647
648    @GuardedBy("mPackages")
649    private boolean mDexOptDialogShown;
650
651    /** The location for ASEC container files on internal storage. */
652    final String mAsecInternalPath;
653
654    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
655    // LOCK HELD.  Can be called with mInstallLock held.
656    @GuardedBy("mInstallLock")
657    final Installer mInstaller;
658
659    /** Directory where installed third-party apps stored */
660    final File mAppInstallDir;
661
662    /**
663     * Directory to which applications installed internally have their
664     * 32 bit native libraries copied.
665     */
666    private File mAppLib32InstallDir;
667
668    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
669    // apps.
670    final File mDrmAppPrivateInstallDir;
671
672    // ----------------------------------------------------------------
673
674    // Lock for state used when installing and doing other long running
675    // operations.  Methods that must be called with this lock held have
676    // the suffix "LI".
677    final Object mInstallLock = new Object();
678
679    // ----------------------------------------------------------------
680
681    // Keys are String (package name), values are Package.  This also serves
682    // as the lock for the global state.  Methods that must be called with
683    // this lock held have the prefix "LP".
684    @GuardedBy("mPackages")
685    final ArrayMap<String, PackageParser.Package> mPackages =
686            new ArrayMap<String, PackageParser.Package>();
687
688    final ArrayMap<String, Set<String>> mKnownCodebase =
689            new ArrayMap<String, Set<String>>();
690
691    // Keys are isolated uids and values are the uid of the application
692    // that created the isolated proccess.
693    @GuardedBy("mPackages")
694    final SparseIntArray mIsolatedOwners = new SparseIntArray();
695
696    /**
697     * Tracks new system packages [received in an OTA] that we expect to
698     * find updated user-installed versions. Keys are package name, values
699     * are package location.
700     */
701    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
702    /**
703     * Tracks high priority intent filters for protected actions. During boot, certain
704     * filter actions are protected and should never be allowed to have a high priority
705     * intent filter for them. However, there is one, and only one exception -- the
706     * setup wizard. It must be able to define a high priority intent filter for these
707     * actions to ensure there are no escapes from the wizard. We need to delay processing
708     * of these during boot as we need to look at all of the system packages in order
709     * to know which component is the setup wizard.
710     */
711    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
712    /**
713     * Whether or not processing protected filters should be deferred.
714     */
715    private boolean mDeferProtectedFilters = true;
716
717    /**
718     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
719     */
720    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
721    /**
722     * Whether or not system app permissions should be promoted from install to runtime.
723     */
724    boolean mPromoteSystemApps;
725
726    @GuardedBy("mPackages")
727    final Settings mSettings;
728
729    /**
730     * Set of package names that are currently "frozen", which means active
731     * surgery is being done on the code/data for that package. The platform
732     * will refuse to launch frozen packages to avoid race conditions.
733     *
734     * @see PackageFreezer
735     */
736    @GuardedBy("mPackages")
737    final ArraySet<String> mFrozenPackages = new ArraySet<>();
738
739    final ProtectedPackages mProtectedPackages;
740
741    @GuardedBy("mLoadedVolumes")
742    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
743
744    boolean mFirstBoot;
745
746    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
747
748    // System configuration read by SystemConfig.
749    final int[] mGlobalGids;
750    final SparseArray<ArraySet<String>> mSystemPermissions;
751    @GuardedBy("mAvailableFeatures")
752    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
753
754    // If mac_permissions.xml was found for seinfo labeling.
755    boolean mFoundPolicyFile;
756
757    private final InstantAppRegistry mInstantAppRegistry;
758
759    @GuardedBy("mPackages")
760    int mChangedPackagesSequenceNumber;
761    /**
762     * List of changed [installed, removed or updated] packages.
763     * mapping from user id -> sequence number -> package name
764     */
765    @GuardedBy("mPackages")
766    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
767    /**
768     * The sequence number of the last change to a package.
769     * mapping from user id -> package name -> sequence number
770     */
771    @GuardedBy("mPackages")
772    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
773
774    class PackageParserCallback implements PackageParser.Callback {
775        @Override public final boolean hasFeature(String feature) {
776            return PackageManagerService.this.hasSystemFeature(feature, 0);
777        }
778
779        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
780                Collection<PackageParser.Package> allPackages, String targetPackageName) {
781            List<PackageParser.Package> overlayPackages = null;
782            for (PackageParser.Package p : allPackages) {
783                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
784                    if (overlayPackages == null) {
785                        overlayPackages = new ArrayList<PackageParser.Package>();
786                    }
787                    overlayPackages.add(p);
788                }
789            }
790            if (overlayPackages != null) {
791                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
792                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
793                        return p1.mOverlayPriority - p2.mOverlayPriority;
794                    }
795                };
796                Collections.sort(overlayPackages, cmp);
797            }
798            return overlayPackages;
799        }
800
801        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
802                String targetPackageName, String targetPath) {
803            if ("android".equals(targetPackageName)) {
804                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
805                // native AssetManager.
806                return null;
807            }
808            List<PackageParser.Package> overlayPackages =
809                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
810            if (overlayPackages == null || overlayPackages.isEmpty()) {
811                return null;
812            }
813            List<String> overlayPathList = null;
814            for (PackageParser.Package overlayPackage : overlayPackages) {
815                if (targetPath == null) {
816                    if (overlayPathList == null) {
817                        overlayPathList = new ArrayList<String>();
818                    }
819                    overlayPathList.add(overlayPackage.baseCodePath);
820                    continue;
821                }
822
823                try {
824                    // Creates idmaps for system to parse correctly the Android manifest of the
825                    // target package.
826                    //
827                    // OverlayManagerService will update each of them with a correct gid from its
828                    // target package app id.
829                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
830                            UserHandle.getSharedAppGid(
831                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
832                    if (overlayPathList == null) {
833                        overlayPathList = new ArrayList<String>();
834                    }
835                    overlayPathList.add(overlayPackage.baseCodePath);
836                } catch (InstallerException e) {
837                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
838                            overlayPackage.baseCodePath);
839                }
840            }
841            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
842        }
843
844        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
845            synchronized (mPackages) {
846                return getStaticOverlayPathsLocked(
847                        mPackages.values(), targetPackageName, targetPath);
848            }
849        }
850
851        @Override public final String[] getOverlayApks(String targetPackageName) {
852            return getStaticOverlayPaths(targetPackageName, null);
853        }
854
855        @Override public final String[] getOverlayPaths(String targetPackageName,
856                String targetPath) {
857            return getStaticOverlayPaths(targetPackageName, targetPath);
858        }
859    };
860
861    class ParallelPackageParserCallback extends PackageParserCallback {
862        List<PackageParser.Package> mOverlayPackages = null;
863
864        void findStaticOverlayPackages() {
865            synchronized (mPackages) {
866                for (PackageParser.Package p : mPackages.values()) {
867                    if (p.mIsStaticOverlay) {
868                        if (mOverlayPackages == null) {
869                            mOverlayPackages = new ArrayList<PackageParser.Package>();
870                        }
871                        mOverlayPackages.add(p);
872                    }
873                }
874            }
875        }
876
877        @Override
878        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
879            // We can trust mOverlayPackages without holding mPackages because package uninstall
880            // can't happen while running parallel parsing.
881            // Moreover holding mPackages on each parsing thread causes dead-lock.
882            return mOverlayPackages == null ? null :
883                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
884        }
885    }
886
887    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
888    final ParallelPackageParserCallback mParallelPackageParserCallback =
889            new ParallelPackageParserCallback();
890
891    public static final class SharedLibraryEntry {
892        public final @Nullable String path;
893        public final @Nullable String apk;
894        public final @NonNull SharedLibraryInfo info;
895
896        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
897                String declaringPackageName, int declaringPackageVersionCode) {
898            path = _path;
899            apk = _apk;
900            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
901                    declaringPackageName, declaringPackageVersionCode), null);
902        }
903    }
904
905    // Currently known shared libraries.
906    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
907    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
908            new ArrayMap<>();
909
910    // All available activities, for your resolving pleasure.
911    final ActivityIntentResolver mActivities =
912            new ActivityIntentResolver();
913
914    // All available receivers, for your resolving pleasure.
915    final ActivityIntentResolver mReceivers =
916            new ActivityIntentResolver();
917
918    // All available services, for your resolving pleasure.
919    final ServiceIntentResolver mServices = new ServiceIntentResolver();
920
921    // All available providers, for your resolving pleasure.
922    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
923
924    // Mapping from provider base names (first directory in content URI codePath)
925    // to the provider information.
926    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
927            new ArrayMap<String, PackageParser.Provider>();
928
929    // Mapping from instrumentation class names to info about them.
930    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
931            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
932
933    // Mapping from permission names to info about them.
934    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
935            new ArrayMap<String, PackageParser.PermissionGroup>();
936
937    // Packages whose data we have transfered into another package, thus
938    // should no longer exist.
939    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
940
941    // Broadcast actions that are only available to the system.
942    @GuardedBy("mProtectedBroadcasts")
943    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
944
945    /** List of packages waiting for verification. */
946    final SparseArray<PackageVerificationState> mPendingVerification
947            = new SparseArray<PackageVerificationState>();
948
949    /** Set of packages associated with each app op permission. */
950    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
951
952    final PackageInstallerService mInstallerService;
953
954    private final PackageDexOptimizer mPackageDexOptimizer;
955    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
956    // is used by other apps).
957    private final DexManager mDexManager;
958
959    private AtomicInteger mNextMoveId = new AtomicInteger();
960    private final MoveCallbacks mMoveCallbacks;
961
962    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
963
964    // Cache of users who need badging.
965    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
966
967    /** Token for keys in mPendingVerification. */
968    private int mPendingVerificationToken = 0;
969
970    volatile boolean mSystemReady;
971    volatile boolean mSafeMode;
972    volatile boolean mHasSystemUidErrors;
973    private volatile boolean mEphemeralAppsDisabled;
974
975    ApplicationInfo mAndroidApplication;
976    final ActivityInfo mResolveActivity = new ActivityInfo();
977    final ResolveInfo mResolveInfo = new ResolveInfo();
978    ComponentName mResolveComponentName;
979    PackageParser.Package mPlatformPackage;
980    ComponentName mCustomResolverComponentName;
981
982    boolean mResolverReplaced = false;
983
984    private final @Nullable ComponentName mIntentFilterVerifierComponent;
985    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
986
987    private int mIntentFilterVerificationToken = 0;
988
989    /** The service connection to the ephemeral resolver */
990    final EphemeralResolverConnection mInstantAppResolverConnection;
991    /** Component used to show resolver settings for Instant Apps */
992    final ComponentName mInstantAppResolverSettingsComponent;
993
994    /** Activity used to install instant applications */
995    ActivityInfo mInstantAppInstallerActivity;
996    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
997
998    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
999            = new SparseArray<IntentFilterVerificationState>();
1000
1001    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
1002
1003    // List of packages names to keep cached, even if they are uninstalled for all users
1004    private List<String> mKeepUninstalledPackages;
1005
1006    private UserManagerInternal mUserManagerInternal;
1007
1008    private DeviceIdleController.LocalService mDeviceIdleController;
1009
1010    private File mCacheDir;
1011
1012    private ArraySet<String> mPrivappPermissionsViolations;
1013
1014    private Future<?> mPrepareAppDataFuture;
1015
1016    private static class IFVerificationParams {
1017        PackageParser.Package pkg;
1018        boolean replacing;
1019        int userId;
1020        int verifierUid;
1021
1022        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1023                int _userId, int _verifierUid) {
1024            pkg = _pkg;
1025            replacing = _replacing;
1026            userId = _userId;
1027            replacing = _replacing;
1028            verifierUid = _verifierUid;
1029        }
1030    }
1031
1032    private interface IntentFilterVerifier<T extends IntentFilter> {
1033        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1034                                               T filter, String packageName);
1035        void startVerifications(int userId);
1036        void receiveVerificationResponse(int verificationId);
1037    }
1038
1039    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1040        private Context mContext;
1041        private ComponentName mIntentFilterVerifierComponent;
1042        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1043
1044        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1045            mContext = context;
1046            mIntentFilterVerifierComponent = verifierComponent;
1047        }
1048
1049        private String getDefaultScheme() {
1050            return IntentFilter.SCHEME_HTTPS;
1051        }
1052
1053        @Override
1054        public void startVerifications(int userId) {
1055            // Launch verifications requests
1056            int count = mCurrentIntentFilterVerifications.size();
1057            for (int n=0; n<count; n++) {
1058                int verificationId = mCurrentIntentFilterVerifications.get(n);
1059                final IntentFilterVerificationState ivs =
1060                        mIntentFilterVerificationStates.get(verificationId);
1061
1062                String packageName = ivs.getPackageName();
1063
1064                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1065                final int filterCount = filters.size();
1066                ArraySet<String> domainsSet = new ArraySet<>();
1067                for (int m=0; m<filterCount; m++) {
1068                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1069                    domainsSet.addAll(filter.getHostsList());
1070                }
1071                synchronized (mPackages) {
1072                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1073                            packageName, domainsSet) != null) {
1074                        scheduleWriteSettingsLocked();
1075                    }
1076                }
1077                sendVerificationRequest(verificationId, ivs);
1078            }
1079            mCurrentIntentFilterVerifications.clear();
1080        }
1081
1082        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1083            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1084            verificationIntent.putExtra(
1085                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1086                    verificationId);
1087            verificationIntent.putExtra(
1088                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1089                    getDefaultScheme());
1090            verificationIntent.putExtra(
1091                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1092                    ivs.getHostsString());
1093            verificationIntent.putExtra(
1094                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1095                    ivs.getPackageName());
1096            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1097            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1098
1099            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1100            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1101                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1102                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1103
1104            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1105            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1106                    "Sending IntentFilter verification broadcast");
1107        }
1108
1109        public void receiveVerificationResponse(int verificationId) {
1110            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1111
1112            final boolean verified = ivs.isVerified();
1113
1114            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1115            final int count = filters.size();
1116            if (DEBUG_DOMAIN_VERIFICATION) {
1117                Slog.i(TAG, "Received verification response " + verificationId
1118                        + " for " + count + " filters, verified=" + verified);
1119            }
1120            for (int n=0; n<count; n++) {
1121                PackageParser.ActivityIntentInfo filter = filters.get(n);
1122                filter.setVerified(verified);
1123
1124                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1125                        + " verified with result:" + verified + " and hosts:"
1126                        + ivs.getHostsString());
1127            }
1128
1129            mIntentFilterVerificationStates.remove(verificationId);
1130
1131            final String packageName = ivs.getPackageName();
1132            IntentFilterVerificationInfo ivi = null;
1133
1134            synchronized (mPackages) {
1135                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1136            }
1137            if (ivi == null) {
1138                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1139                        + verificationId + " packageName:" + packageName);
1140                return;
1141            }
1142            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1143                    "Updating IntentFilterVerificationInfo for package " + packageName
1144                            +" verificationId:" + verificationId);
1145
1146            synchronized (mPackages) {
1147                if (verified) {
1148                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1149                } else {
1150                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1151                }
1152                scheduleWriteSettingsLocked();
1153
1154                final int userId = ivs.getUserId();
1155                if (userId != UserHandle.USER_ALL) {
1156                    final int userStatus =
1157                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1158
1159                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1160                    boolean needUpdate = false;
1161
1162                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1163                    // already been set by the User thru the Disambiguation dialog
1164                    switch (userStatus) {
1165                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1166                            if (verified) {
1167                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1168                            } else {
1169                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1170                            }
1171                            needUpdate = true;
1172                            break;
1173
1174                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1175                            if (verified) {
1176                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1177                                needUpdate = true;
1178                            }
1179                            break;
1180
1181                        default:
1182                            // Nothing to do
1183                    }
1184
1185                    if (needUpdate) {
1186                        mSettings.updateIntentFilterVerificationStatusLPw(
1187                                packageName, updatedStatus, userId);
1188                        scheduleWritePackageRestrictionsLocked(userId);
1189                    }
1190                }
1191            }
1192        }
1193
1194        @Override
1195        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1196                    ActivityIntentInfo filter, String packageName) {
1197            if (!hasValidDomains(filter)) {
1198                return false;
1199            }
1200            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1201            if (ivs == null) {
1202                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1203                        packageName);
1204            }
1205            if (DEBUG_DOMAIN_VERIFICATION) {
1206                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1207            }
1208            ivs.addFilter(filter);
1209            return true;
1210        }
1211
1212        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1213                int userId, int verificationId, String packageName) {
1214            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1215                    verifierUid, userId, packageName);
1216            ivs.setPendingState();
1217            synchronized (mPackages) {
1218                mIntentFilterVerificationStates.append(verificationId, ivs);
1219                mCurrentIntentFilterVerifications.add(verificationId);
1220            }
1221            return ivs;
1222        }
1223    }
1224
1225    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1226        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1227                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1228                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1229    }
1230
1231    // Set of pending broadcasts for aggregating enable/disable of components.
1232    static class PendingPackageBroadcasts {
1233        // for each user id, a map of <package name -> components within that package>
1234        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1235
1236        public PendingPackageBroadcasts() {
1237            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1238        }
1239
1240        public ArrayList<String> get(int userId, String packageName) {
1241            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1242            return packages.get(packageName);
1243        }
1244
1245        public void put(int userId, String packageName, ArrayList<String> components) {
1246            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1247            packages.put(packageName, components);
1248        }
1249
1250        public void remove(int userId, String packageName) {
1251            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1252            if (packages != null) {
1253                packages.remove(packageName);
1254            }
1255        }
1256
1257        public void remove(int userId) {
1258            mUidMap.remove(userId);
1259        }
1260
1261        public int userIdCount() {
1262            return mUidMap.size();
1263        }
1264
1265        public int userIdAt(int n) {
1266            return mUidMap.keyAt(n);
1267        }
1268
1269        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1270            return mUidMap.get(userId);
1271        }
1272
1273        public int size() {
1274            // total number of pending broadcast entries across all userIds
1275            int num = 0;
1276            for (int i = 0; i< mUidMap.size(); i++) {
1277                num += mUidMap.valueAt(i).size();
1278            }
1279            return num;
1280        }
1281
1282        public void clear() {
1283            mUidMap.clear();
1284        }
1285
1286        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1287            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1288            if (map == null) {
1289                map = new ArrayMap<String, ArrayList<String>>();
1290                mUidMap.put(userId, map);
1291            }
1292            return map;
1293        }
1294    }
1295    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1296
1297    // Service Connection to remote media container service to copy
1298    // package uri's from external media onto secure containers
1299    // or internal storage.
1300    private IMediaContainerService mContainerService = null;
1301
1302    static final int SEND_PENDING_BROADCAST = 1;
1303    static final int MCS_BOUND = 3;
1304    static final int END_COPY = 4;
1305    static final int INIT_COPY = 5;
1306    static final int MCS_UNBIND = 6;
1307    static final int START_CLEANING_PACKAGE = 7;
1308    static final int FIND_INSTALL_LOC = 8;
1309    static final int POST_INSTALL = 9;
1310    static final int MCS_RECONNECT = 10;
1311    static final int MCS_GIVE_UP = 11;
1312    static final int UPDATED_MEDIA_STATUS = 12;
1313    static final int WRITE_SETTINGS = 13;
1314    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1315    static final int PACKAGE_VERIFIED = 15;
1316    static final int CHECK_PENDING_VERIFICATION = 16;
1317    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1318    static final int INTENT_FILTER_VERIFIED = 18;
1319    static final int WRITE_PACKAGE_LIST = 19;
1320    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1321
1322    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1323
1324    // Delay time in millisecs
1325    static final int BROADCAST_DELAY = 10 * 1000;
1326
1327    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1328            2 * 60 * 60 * 1000L; /* two hours */
1329
1330    static UserManagerService sUserManager;
1331
1332    // Stores a list of users whose package restrictions file needs to be updated
1333    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1334
1335    final private DefaultContainerConnection mDefContainerConn =
1336            new DefaultContainerConnection();
1337    class DefaultContainerConnection implements ServiceConnection {
1338        public void onServiceConnected(ComponentName name, IBinder service) {
1339            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1340            final IMediaContainerService imcs = IMediaContainerService.Stub
1341                    .asInterface(Binder.allowBlocking(service));
1342            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1343        }
1344
1345        public void onServiceDisconnected(ComponentName name) {
1346            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1347        }
1348    }
1349
1350    // Recordkeeping of restore-after-install operations that are currently in flight
1351    // between the Package Manager and the Backup Manager
1352    static class PostInstallData {
1353        public InstallArgs args;
1354        public PackageInstalledInfo res;
1355
1356        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1357            args = _a;
1358            res = _r;
1359        }
1360    }
1361
1362    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1363    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1364
1365    // XML tags for backup/restore of various bits of state
1366    private static final String TAG_PREFERRED_BACKUP = "pa";
1367    private static final String TAG_DEFAULT_APPS = "da";
1368    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1369
1370    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1371    private static final String TAG_ALL_GRANTS = "rt-grants";
1372    private static final String TAG_GRANT = "grant";
1373    private static final String ATTR_PACKAGE_NAME = "pkg";
1374
1375    private static final String TAG_PERMISSION = "perm";
1376    private static final String ATTR_PERMISSION_NAME = "name";
1377    private static final String ATTR_IS_GRANTED = "g";
1378    private static final String ATTR_USER_SET = "set";
1379    private static final String ATTR_USER_FIXED = "fixed";
1380    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1381
1382    // System/policy permission grants are not backed up
1383    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1384            FLAG_PERMISSION_POLICY_FIXED
1385            | FLAG_PERMISSION_SYSTEM_FIXED
1386            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1387
1388    // And we back up these user-adjusted states
1389    private static final int USER_RUNTIME_GRANT_MASK =
1390            FLAG_PERMISSION_USER_SET
1391            | FLAG_PERMISSION_USER_FIXED
1392            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1393
1394    final @Nullable String mRequiredVerifierPackage;
1395    final @NonNull String mRequiredInstallerPackage;
1396    final @NonNull String mRequiredUninstallerPackage;
1397    final @Nullable String mSetupWizardPackage;
1398    final @Nullable String mStorageManagerPackage;
1399    final @NonNull String mServicesSystemSharedLibraryPackageName;
1400    final @NonNull String mSharedSystemSharedLibraryPackageName;
1401
1402    final boolean mPermissionReviewRequired;
1403
1404    private final PackageUsage mPackageUsage = new PackageUsage();
1405    private final CompilerStats mCompilerStats = new CompilerStats();
1406
1407    class PackageHandler extends Handler {
1408        private boolean mBound = false;
1409        final ArrayList<HandlerParams> mPendingInstalls =
1410            new ArrayList<HandlerParams>();
1411
1412        private boolean connectToService() {
1413            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1414                    " DefaultContainerService");
1415            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1416            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1417            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1418                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1419                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1420                mBound = true;
1421                return true;
1422            }
1423            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1424            return false;
1425        }
1426
1427        private void disconnectService() {
1428            mContainerService = null;
1429            mBound = false;
1430            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1431            mContext.unbindService(mDefContainerConn);
1432            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1433        }
1434
1435        PackageHandler(Looper looper) {
1436            super(looper);
1437        }
1438
1439        public void handleMessage(Message msg) {
1440            try {
1441                doHandleMessage(msg);
1442            } finally {
1443                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1444            }
1445        }
1446
1447        void doHandleMessage(Message msg) {
1448            switch (msg.what) {
1449                case INIT_COPY: {
1450                    HandlerParams params = (HandlerParams) msg.obj;
1451                    int idx = mPendingInstalls.size();
1452                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1453                    // If a bind was already initiated we dont really
1454                    // need to do anything. The pending install
1455                    // will be processed later on.
1456                    if (!mBound) {
1457                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1458                                System.identityHashCode(mHandler));
1459                        // If this is the only one pending we might
1460                        // have to bind to the service again.
1461                        if (!connectToService()) {
1462                            Slog.e(TAG, "Failed to bind to media container service");
1463                            params.serviceError();
1464                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1465                                    System.identityHashCode(mHandler));
1466                            if (params.traceMethod != null) {
1467                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1468                                        params.traceCookie);
1469                            }
1470                            return;
1471                        } else {
1472                            // Once we bind to the service, the first
1473                            // pending request will be processed.
1474                            mPendingInstalls.add(idx, params);
1475                        }
1476                    } else {
1477                        mPendingInstalls.add(idx, params);
1478                        // Already bound to the service. Just make
1479                        // sure we trigger off processing the first request.
1480                        if (idx == 0) {
1481                            mHandler.sendEmptyMessage(MCS_BOUND);
1482                        }
1483                    }
1484                    break;
1485                }
1486                case MCS_BOUND: {
1487                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1488                    if (msg.obj != null) {
1489                        mContainerService = (IMediaContainerService) msg.obj;
1490                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1491                                System.identityHashCode(mHandler));
1492                    }
1493                    if (mContainerService == null) {
1494                        if (!mBound) {
1495                            // Something seriously wrong since we are not bound and we are not
1496                            // waiting for connection. Bail out.
1497                            Slog.e(TAG, "Cannot bind to media container service");
1498                            for (HandlerParams params : mPendingInstalls) {
1499                                // Indicate service bind error
1500                                params.serviceError();
1501                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1502                                        System.identityHashCode(params));
1503                                if (params.traceMethod != null) {
1504                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1505                                            params.traceMethod, params.traceCookie);
1506                                }
1507                                return;
1508                            }
1509                            mPendingInstalls.clear();
1510                        } else {
1511                            Slog.w(TAG, "Waiting to connect to media container service");
1512                        }
1513                    } else if (mPendingInstalls.size() > 0) {
1514                        HandlerParams params = mPendingInstalls.get(0);
1515                        if (params != null) {
1516                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1517                                    System.identityHashCode(params));
1518                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1519                            if (params.startCopy()) {
1520                                // We are done...  look for more work or to
1521                                // go idle.
1522                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1523                                        "Checking for more work or unbind...");
1524                                // Delete pending install
1525                                if (mPendingInstalls.size() > 0) {
1526                                    mPendingInstalls.remove(0);
1527                                }
1528                                if (mPendingInstalls.size() == 0) {
1529                                    if (mBound) {
1530                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1531                                                "Posting delayed MCS_UNBIND");
1532                                        removeMessages(MCS_UNBIND);
1533                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1534                                        // Unbind after a little delay, to avoid
1535                                        // continual thrashing.
1536                                        sendMessageDelayed(ubmsg, 10000);
1537                                    }
1538                                } else {
1539                                    // There are more pending requests in queue.
1540                                    // Just post MCS_BOUND message to trigger processing
1541                                    // of next pending install.
1542                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1543                                            "Posting MCS_BOUND for next work");
1544                                    mHandler.sendEmptyMessage(MCS_BOUND);
1545                                }
1546                            }
1547                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1548                        }
1549                    } else {
1550                        // Should never happen ideally.
1551                        Slog.w(TAG, "Empty queue");
1552                    }
1553                    break;
1554                }
1555                case MCS_RECONNECT: {
1556                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1557                    if (mPendingInstalls.size() > 0) {
1558                        if (mBound) {
1559                            disconnectService();
1560                        }
1561                        if (!connectToService()) {
1562                            Slog.e(TAG, "Failed to bind to media container service");
1563                            for (HandlerParams params : mPendingInstalls) {
1564                                // Indicate service bind error
1565                                params.serviceError();
1566                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1567                                        System.identityHashCode(params));
1568                            }
1569                            mPendingInstalls.clear();
1570                        }
1571                    }
1572                    break;
1573                }
1574                case MCS_UNBIND: {
1575                    // If there is no actual work left, then time to unbind.
1576                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1577
1578                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1579                        if (mBound) {
1580                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1581
1582                            disconnectService();
1583                        }
1584                    } else if (mPendingInstalls.size() > 0) {
1585                        // There are more pending requests in queue.
1586                        // Just post MCS_BOUND message to trigger processing
1587                        // of next pending install.
1588                        mHandler.sendEmptyMessage(MCS_BOUND);
1589                    }
1590
1591                    break;
1592                }
1593                case MCS_GIVE_UP: {
1594                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1595                    HandlerParams params = mPendingInstalls.remove(0);
1596                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1597                            System.identityHashCode(params));
1598                    break;
1599                }
1600                case SEND_PENDING_BROADCAST: {
1601                    String packages[];
1602                    ArrayList<String> components[];
1603                    int size = 0;
1604                    int uids[];
1605                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1606                    synchronized (mPackages) {
1607                        if (mPendingBroadcasts == null) {
1608                            return;
1609                        }
1610                        size = mPendingBroadcasts.size();
1611                        if (size <= 0) {
1612                            // Nothing to be done. Just return
1613                            return;
1614                        }
1615                        packages = new String[size];
1616                        components = new ArrayList[size];
1617                        uids = new int[size];
1618                        int i = 0;  // filling out the above arrays
1619
1620                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1621                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1622                            Iterator<Map.Entry<String, ArrayList<String>>> it
1623                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1624                                            .entrySet().iterator();
1625                            while (it.hasNext() && i < size) {
1626                                Map.Entry<String, ArrayList<String>> ent = it.next();
1627                                packages[i] = ent.getKey();
1628                                components[i] = ent.getValue();
1629                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1630                                uids[i] = (ps != null)
1631                                        ? UserHandle.getUid(packageUserId, ps.appId)
1632                                        : -1;
1633                                i++;
1634                            }
1635                        }
1636                        size = i;
1637                        mPendingBroadcasts.clear();
1638                    }
1639                    // Send broadcasts
1640                    for (int i = 0; i < size; i++) {
1641                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1642                    }
1643                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1644                    break;
1645                }
1646                case START_CLEANING_PACKAGE: {
1647                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1648                    final String packageName = (String)msg.obj;
1649                    final int userId = msg.arg1;
1650                    final boolean andCode = msg.arg2 != 0;
1651                    synchronized (mPackages) {
1652                        if (userId == UserHandle.USER_ALL) {
1653                            int[] users = sUserManager.getUserIds();
1654                            for (int user : users) {
1655                                mSettings.addPackageToCleanLPw(
1656                                        new PackageCleanItem(user, packageName, andCode));
1657                            }
1658                        } else {
1659                            mSettings.addPackageToCleanLPw(
1660                                    new PackageCleanItem(userId, packageName, andCode));
1661                        }
1662                    }
1663                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1664                    startCleaningPackages();
1665                } break;
1666                case POST_INSTALL: {
1667                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1668
1669                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1670                    final boolean didRestore = (msg.arg2 != 0);
1671                    mRunningInstalls.delete(msg.arg1);
1672
1673                    if (data != null) {
1674                        InstallArgs args = data.args;
1675                        PackageInstalledInfo parentRes = data.res;
1676
1677                        final boolean grantPermissions = (args.installFlags
1678                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1679                        final boolean killApp = (args.installFlags
1680                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1681                        final boolean virtualPreload = ((args.installFlags
1682                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1683                        final String[] grantedPermissions = args.installGrantPermissions;
1684
1685                        // Handle the parent package
1686                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1687                                virtualPreload, grantedPermissions, didRestore,
1688                                args.installerPackageName, args.observer);
1689
1690                        // Handle the child packages
1691                        final int childCount = (parentRes.addedChildPackages != null)
1692                                ? parentRes.addedChildPackages.size() : 0;
1693                        for (int i = 0; i < childCount; i++) {
1694                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1695                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1696                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1697                                    args.installerPackageName, args.observer);
1698                        }
1699
1700                        // Log tracing if needed
1701                        if (args.traceMethod != null) {
1702                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1703                                    args.traceCookie);
1704                        }
1705                    } else {
1706                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1707                    }
1708
1709                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1710                } break;
1711                case UPDATED_MEDIA_STATUS: {
1712                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1713                    boolean reportStatus = msg.arg1 == 1;
1714                    boolean doGc = msg.arg2 == 1;
1715                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1716                    if (doGc) {
1717                        // Force a gc to clear up stale containers.
1718                        Runtime.getRuntime().gc();
1719                    }
1720                    if (msg.obj != null) {
1721                        @SuppressWarnings("unchecked")
1722                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1723                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1724                        // Unload containers
1725                        unloadAllContainers(args);
1726                    }
1727                    if (reportStatus) {
1728                        try {
1729                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1730                                    "Invoking StorageManagerService call back");
1731                            PackageHelper.getStorageManager().finishMediaUpdate();
1732                        } catch (RemoteException e) {
1733                            Log.e(TAG, "StorageManagerService not running?");
1734                        }
1735                    }
1736                } break;
1737                case WRITE_SETTINGS: {
1738                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1739                    synchronized (mPackages) {
1740                        removeMessages(WRITE_SETTINGS);
1741                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1742                        mSettings.writeLPr();
1743                        mDirtyUsers.clear();
1744                    }
1745                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1746                } break;
1747                case WRITE_PACKAGE_RESTRICTIONS: {
1748                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1749                    synchronized (mPackages) {
1750                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1751                        for (int userId : mDirtyUsers) {
1752                            mSettings.writePackageRestrictionsLPr(userId);
1753                        }
1754                        mDirtyUsers.clear();
1755                    }
1756                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1757                } break;
1758                case WRITE_PACKAGE_LIST: {
1759                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1760                    synchronized (mPackages) {
1761                        removeMessages(WRITE_PACKAGE_LIST);
1762                        mSettings.writePackageListLPr(msg.arg1);
1763                    }
1764                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1765                } break;
1766                case CHECK_PENDING_VERIFICATION: {
1767                    final int verificationId = msg.arg1;
1768                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1769
1770                    if ((state != null) && !state.timeoutExtended()) {
1771                        final InstallArgs args = state.getInstallArgs();
1772                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1773
1774                        Slog.i(TAG, "Verification timed out for " + originUri);
1775                        mPendingVerification.remove(verificationId);
1776
1777                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1778
1779                        final UserHandle user = args.getUser();
1780                        if (getDefaultVerificationResponse(user)
1781                                == PackageManager.VERIFICATION_ALLOW) {
1782                            Slog.i(TAG, "Continuing with installation of " + originUri);
1783                            state.setVerifierResponse(Binder.getCallingUid(),
1784                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1785                            broadcastPackageVerified(verificationId, originUri,
1786                                    PackageManager.VERIFICATION_ALLOW, user);
1787                            try {
1788                                ret = args.copyApk(mContainerService, true);
1789                            } catch (RemoteException e) {
1790                                Slog.e(TAG, "Could not contact the ContainerService");
1791                            }
1792                        } else {
1793                            broadcastPackageVerified(verificationId, originUri,
1794                                    PackageManager.VERIFICATION_REJECT, user);
1795                        }
1796
1797                        Trace.asyncTraceEnd(
1798                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1799
1800                        processPendingInstall(args, ret);
1801                        mHandler.sendEmptyMessage(MCS_UNBIND);
1802                    }
1803                    break;
1804                }
1805                case PACKAGE_VERIFIED: {
1806                    final int verificationId = msg.arg1;
1807
1808                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1809                    if (state == null) {
1810                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1811                        break;
1812                    }
1813
1814                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1815
1816                    state.setVerifierResponse(response.callerUid, response.code);
1817
1818                    if (state.isVerificationComplete()) {
1819                        mPendingVerification.remove(verificationId);
1820
1821                        final InstallArgs args = state.getInstallArgs();
1822                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1823
1824                        int ret;
1825                        if (state.isInstallAllowed()) {
1826                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1827                            broadcastPackageVerified(verificationId, originUri,
1828                                    response.code, state.getInstallArgs().getUser());
1829                            try {
1830                                ret = args.copyApk(mContainerService, true);
1831                            } catch (RemoteException e) {
1832                                Slog.e(TAG, "Could not contact the ContainerService");
1833                            }
1834                        } else {
1835                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1836                        }
1837
1838                        Trace.asyncTraceEnd(
1839                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1840
1841                        processPendingInstall(args, ret);
1842                        mHandler.sendEmptyMessage(MCS_UNBIND);
1843                    }
1844
1845                    break;
1846                }
1847                case START_INTENT_FILTER_VERIFICATIONS: {
1848                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1849                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1850                            params.replacing, params.pkg);
1851                    break;
1852                }
1853                case INTENT_FILTER_VERIFIED: {
1854                    final int verificationId = msg.arg1;
1855
1856                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1857                            verificationId);
1858                    if (state == null) {
1859                        Slog.w(TAG, "Invalid IntentFilter verification token "
1860                                + verificationId + " received");
1861                        break;
1862                    }
1863
1864                    final int userId = state.getUserId();
1865
1866                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1867                            "Processing IntentFilter verification with token:"
1868                            + verificationId + " and userId:" + userId);
1869
1870                    final IntentFilterVerificationResponse response =
1871                            (IntentFilterVerificationResponse) msg.obj;
1872
1873                    state.setVerifierResponse(response.callerUid, response.code);
1874
1875                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1876                            "IntentFilter verification with token:" + verificationId
1877                            + " and userId:" + userId
1878                            + " is settings verifier response with response code:"
1879                            + response.code);
1880
1881                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1882                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1883                                + response.getFailedDomainsString());
1884                    }
1885
1886                    if (state.isVerificationComplete()) {
1887                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1888                    } else {
1889                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1890                                "IntentFilter verification with token:" + verificationId
1891                                + " was not said to be complete");
1892                    }
1893
1894                    break;
1895                }
1896                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1897                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1898                            mInstantAppResolverConnection,
1899                            (InstantAppRequest) msg.obj,
1900                            mInstantAppInstallerActivity,
1901                            mHandler);
1902                }
1903            }
1904        }
1905    }
1906
1907    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1908            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1909            boolean launchedForRestore, String installerPackage,
1910            IPackageInstallObserver2 installObserver) {
1911        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1912            // Send the removed broadcasts
1913            if (res.removedInfo != null) {
1914                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1915            }
1916
1917            // Now that we successfully installed the package, grant runtime
1918            // permissions if requested before broadcasting the install. Also
1919            // for legacy apps in permission review mode we clear the permission
1920            // review flag which is used to emulate runtime permissions for
1921            // legacy apps.
1922            if (grantPermissions) {
1923                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1924            }
1925
1926            final boolean update = res.removedInfo != null
1927                    && res.removedInfo.removedPackage != null;
1928            final String origInstallerPackageName = res.removedInfo != null
1929                    ? res.removedInfo.installerPackageName : null;
1930
1931            // If this is the first time we have child packages for a disabled privileged
1932            // app that had no children, we grant requested runtime permissions to the new
1933            // children if the parent on the system image had them already granted.
1934            if (res.pkg.parentPackage != null) {
1935                synchronized (mPackages) {
1936                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1937                }
1938            }
1939
1940            synchronized (mPackages) {
1941                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1942            }
1943
1944            final String packageName = res.pkg.applicationInfo.packageName;
1945
1946            // Determine the set of users who are adding this package for
1947            // the first time vs. those who are seeing an update.
1948            int[] firstUsers = EMPTY_INT_ARRAY;
1949            int[] updateUsers = EMPTY_INT_ARRAY;
1950            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1951            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1952            for (int newUser : res.newUsers) {
1953                if (ps.getInstantApp(newUser)) {
1954                    continue;
1955                }
1956                if (allNewUsers) {
1957                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1958                    continue;
1959                }
1960                boolean isNew = true;
1961                for (int origUser : res.origUsers) {
1962                    if (origUser == newUser) {
1963                        isNew = false;
1964                        break;
1965                    }
1966                }
1967                if (isNew) {
1968                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1969                } else {
1970                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1971                }
1972            }
1973
1974            // Send installed broadcasts if the package is not a static shared lib.
1975            if (res.pkg.staticSharedLibName == null) {
1976                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1977
1978                // Send added for users that see the package for the first time
1979                // sendPackageAddedForNewUsers also deals with system apps
1980                int appId = UserHandle.getAppId(res.uid);
1981                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1982                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
1983                        virtualPreload /*startReceiver*/, appId, firstUsers);
1984
1985                // Send added for users that don't see the package for the first time
1986                Bundle extras = new Bundle(1);
1987                extras.putInt(Intent.EXTRA_UID, res.uid);
1988                if (update) {
1989                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1990                }
1991                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1992                        extras, 0 /*flags*/,
1993                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1994                if (origInstallerPackageName != null) {
1995                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1996                            extras, 0 /*flags*/,
1997                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1998                }
1999
2000                // Send replaced for users that don't see the package for the first time
2001                if (update) {
2002                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2003                            packageName, extras, 0 /*flags*/,
2004                            null /*targetPackage*/, null /*finishedReceiver*/,
2005                            updateUsers);
2006                    if (origInstallerPackageName != null) {
2007                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2008                                extras, 0 /*flags*/,
2009                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
2010                    }
2011                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2012                            null /*package*/, null /*extras*/, 0 /*flags*/,
2013                            packageName /*targetPackage*/,
2014                            null /*finishedReceiver*/, updateUsers);
2015                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2016                    // First-install and we did a restore, so we're responsible for the
2017                    // first-launch broadcast.
2018                    if (DEBUG_BACKUP) {
2019                        Slog.i(TAG, "Post-restore of " + packageName
2020                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2021                    }
2022                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2023                }
2024
2025                // Send broadcast package appeared if forward locked/external for all users
2026                // treat asec-hosted packages like removable media on upgrade
2027                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2028                    if (DEBUG_INSTALL) {
2029                        Slog.i(TAG, "upgrading pkg " + res.pkg
2030                                + " is ASEC-hosted -> AVAILABLE");
2031                    }
2032                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2033                    ArrayList<String> pkgList = new ArrayList<>(1);
2034                    pkgList.add(packageName);
2035                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2036                }
2037            }
2038
2039            // Work that needs to happen on first install within each user
2040            if (firstUsers != null && firstUsers.length > 0) {
2041                synchronized (mPackages) {
2042                    for (int userId : firstUsers) {
2043                        // If this app is a browser and it's newly-installed for some
2044                        // users, clear any default-browser state in those users. The
2045                        // app's nature doesn't depend on the user, so we can just check
2046                        // its browser nature in any user and generalize.
2047                        if (packageIsBrowser(packageName, userId)) {
2048                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2049                        }
2050
2051                        // We may also need to apply pending (restored) runtime
2052                        // permission grants within these users.
2053                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2054                    }
2055                }
2056            }
2057
2058            // Log current value of "unknown sources" setting
2059            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2060                    getUnknownSourcesSettings());
2061
2062            // Remove the replaced package's older resources safely now
2063            // We delete after a gc for applications  on sdcard.
2064            if (res.removedInfo != null && res.removedInfo.args != null) {
2065                Runtime.getRuntime().gc();
2066                synchronized (mInstallLock) {
2067                    res.removedInfo.args.doPostDeleteLI(true);
2068                }
2069            } else {
2070                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2071                // and not block here.
2072                VMRuntime.getRuntime().requestConcurrentGC();
2073            }
2074
2075            // Notify DexManager that the package was installed for new users.
2076            // The updated users should already be indexed and the package code paths
2077            // should not change.
2078            // Don't notify the manager for ephemeral apps as they are not expected to
2079            // survive long enough to benefit of background optimizations.
2080            for (int userId : firstUsers) {
2081                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2082                // There's a race currently where some install events may interleave with an uninstall.
2083                // This can lead to package info being null (b/36642664).
2084                if (info != null) {
2085                    mDexManager.notifyPackageInstalled(info, userId);
2086                }
2087            }
2088        }
2089
2090        // If someone is watching installs - notify them
2091        if (installObserver != null) {
2092            try {
2093                Bundle extras = extrasForInstallResult(res);
2094                installObserver.onPackageInstalled(res.name, res.returnCode,
2095                        res.returnMsg, extras);
2096            } catch (RemoteException e) {
2097                Slog.i(TAG, "Observer no longer exists.");
2098            }
2099        }
2100    }
2101
2102    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2103            PackageParser.Package pkg) {
2104        if (pkg.parentPackage == null) {
2105            return;
2106        }
2107        if (pkg.requestedPermissions == null) {
2108            return;
2109        }
2110        final PackageSetting disabledSysParentPs = mSettings
2111                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2112        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2113                || !disabledSysParentPs.isPrivileged()
2114                || (disabledSysParentPs.childPackageNames != null
2115                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2116            return;
2117        }
2118        final int[] allUserIds = sUserManager.getUserIds();
2119        final int permCount = pkg.requestedPermissions.size();
2120        for (int i = 0; i < permCount; i++) {
2121            String permission = pkg.requestedPermissions.get(i);
2122            BasePermission bp = mSettings.mPermissions.get(permission);
2123            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2124                continue;
2125            }
2126            for (int userId : allUserIds) {
2127                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2128                        permission, userId)) {
2129                    grantRuntimePermission(pkg.packageName, permission, userId);
2130                }
2131            }
2132        }
2133    }
2134
2135    private StorageEventListener mStorageListener = new StorageEventListener() {
2136        @Override
2137        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2138            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2139                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2140                    final String volumeUuid = vol.getFsUuid();
2141
2142                    // Clean up any users or apps that were removed or recreated
2143                    // while this volume was missing
2144                    sUserManager.reconcileUsers(volumeUuid);
2145                    reconcileApps(volumeUuid);
2146
2147                    // Clean up any install sessions that expired or were
2148                    // cancelled while this volume was missing
2149                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2150
2151                    loadPrivatePackages(vol);
2152
2153                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2154                    unloadPrivatePackages(vol);
2155                }
2156            }
2157
2158            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2159                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2160                    updateExternalMediaStatus(true, false);
2161                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2162                    updateExternalMediaStatus(false, false);
2163                }
2164            }
2165        }
2166
2167        @Override
2168        public void onVolumeForgotten(String fsUuid) {
2169            if (TextUtils.isEmpty(fsUuid)) {
2170                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2171                return;
2172            }
2173
2174            // Remove any apps installed on the forgotten volume
2175            synchronized (mPackages) {
2176                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2177                for (PackageSetting ps : packages) {
2178                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2179                    deletePackageVersioned(new VersionedPackage(ps.name,
2180                            PackageManager.VERSION_CODE_HIGHEST),
2181                            new LegacyPackageDeleteObserver(null).getBinder(),
2182                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2183                    // Try very hard to release any references to this package
2184                    // so we don't risk the system server being killed due to
2185                    // open FDs
2186                    AttributeCache.instance().removePackage(ps.name);
2187                }
2188
2189                mSettings.onVolumeForgotten(fsUuid);
2190                mSettings.writeLPr();
2191            }
2192        }
2193    };
2194
2195    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2196            String[] grantedPermissions) {
2197        for (int userId : userIds) {
2198            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2199        }
2200    }
2201
2202    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2203            String[] grantedPermissions) {
2204        PackageSetting ps = (PackageSetting) pkg.mExtras;
2205        if (ps == null) {
2206            return;
2207        }
2208
2209        PermissionsState permissionsState = ps.getPermissionsState();
2210
2211        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2212                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2213
2214        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2215                >= Build.VERSION_CODES.M;
2216
2217        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2218
2219        for (String permission : pkg.requestedPermissions) {
2220            final BasePermission bp;
2221            synchronized (mPackages) {
2222                bp = mSettings.mPermissions.get(permission);
2223            }
2224            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2225                    && (!instantApp || bp.isInstant())
2226                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2227                    && (grantedPermissions == null
2228                           || ArrayUtils.contains(grantedPermissions, permission))) {
2229                final int flags = permissionsState.getPermissionFlags(permission, userId);
2230                if (supportsRuntimePermissions) {
2231                    // Installer cannot change immutable permissions.
2232                    if ((flags & immutableFlags) == 0) {
2233                        grantRuntimePermission(pkg.packageName, permission, userId);
2234                    }
2235                } else if (mPermissionReviewRequired) {
2236                    // In permission review mode we clear the review flag when we
2237                    // are asked to install the app with all permissions granted.
2238                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2239                        updatePermissionFlags(permission, pkg.packageName,
2240                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2241                    }
2242                }
2243            }
2244        }
2245    }
2246
2247    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2248        Bundle extras = null;
2249        switch (res.returnCode) {
2250            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2251                extras = new Bundle();
2252                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2253                        res.origPermission);
2254                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2255                        res.origPackage);
2256                break;
2257            }
2258            case PackageManager.INSTALL_SUCCEEDED: {
2259                extras = new Bundle();
2260                extras.putBoolean(Intent.EXTRA_REPLACING,
2261                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2262                break;
2263            }
2264        }
2265        return extras;
2266    }
2267
2268    void scheduleWriteSettingsLocked() {
2269        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2270            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2271        }
2272    }
2273
2274    void scheduleWritePackageListLocked(int userId) {
2275        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2276            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2277            msg.arg1 = userId;
2278            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2279        }
2280    }
2281
2282    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2283        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2284        scheduleWritePackageRestrictionsLocked(userId);
2285    }
2286
2287    void scheduleWritePackageRestrictionsLocked(int userId) {
2288        final int[] userIds = (userId == UserHandle.USER_ALL)
2289                ? sUserManager.getUserIds() : new int[]{userId};
2290        for (int nextUserId : userIds) {
2291            if (!sUserManager.exists(nextUserId)) return;
2292            mDirtyUsers.add(nextUserId);
2293            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2294                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2295            }
2296        }
2297    }
2298
2299    public static PackageManagerService main(Context context, Installer installer,
2300            boolean factoryTest, boolean onlyCore) {
2301        // Self-check for initial settings.
2302        PackageManagerServiceCompilerMapping.checkProperties();
2303
2304        PackageManagerService m = new PackageManagerService(context, installer,
2305                factoryTest, onlyCore);
2306        m.enableSystemUserPackages();
2307        ServiceManager.addService("package", m);
2308        final PackageManagerNative pmn = m.new PackageManagerNative();
2309        ServiceManager.addService("package_native", pmn);
2310        return m;
2311    }
2312
2313    private void enableSystemUserPackages() {
2314        if (!UserManager.isSplitSystemUser()) {
2315            return;
2316        }
2317        // For system user, enable apps based on the following conditions:
2318        // - app is whitelisted or belong to one of these groups:
2319        //   -- system app which has no launcher icons
2320        //   -- system app which has INTERACT_ACROSS_USERS permission
2321        //   -- system IME app
2322        // - app is not in the blacklist
2323        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2324        Set<String> enableApps = new ArraySet<>();
2325        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2326                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2327                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2328        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2329        enableApps.addAll(wlApps);
2330        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2331                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2332        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2333        enableApps.removeAll(blApps);
2334        Log.i(TAG, "Applications installed for system user: " + enableApps);
2335        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2336                UserHandle.SYSTEM);
2337        final int allAppsSize = allAps.size();
2338        synchronized (mPackages) {
2339            for (int i = 0; i < allAppsSize; i++) {
2340                String pName = allAps.get(i);
2341                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2342                // Should not happen, but we shouldn't be failing if it does
2343                if (pkgSetting == null) {
2344                    continue;
2345                }
2346                boolean install = enableApps.contains(pName);
2347                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2348                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2349                            + " for system user");
2350                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2351                }
2352            }
2353            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2354        }
2355    }
2356
2357    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2358        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2359                Context.DISPLAY_SERVICE);
2360        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2361    }
2362
2363    /**
2364     * Requests that files preopted on a secondary system partition be copied to the data partition
2365     * if possible.  Note that the actual copying of the files is accomplished by init for security
2366     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2367     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2368     */
2369    private static void requestCopyPreoptedFiles() {
2370        final int WAIT_TIME_MS = 100;
2371        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2372        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2373            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2374            // We will wait for up to 100 seconds.
2375            final long timeStart = SystemClock.uptimeMillis();
2376            final long timeEnd = timeStart + 100 * 1000;
2377            long timeNow = timeStart;
2378            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2379                try {
2380                    Thread.sleep(WAIT_TIME_MS);
2381                } catch (InterruptedException e) {
2382                    // Do nothing
2383                }
2384                timeNow = SystemClock.uptimeMillis();
2385                if (timeNow > timeEnd) {
2386                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2387                    Slog.wtf(TAG, "cppreopt did not finish!");
2388                    break;
2389                }
2390            }
2391
2392            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2393        }
2394    }
2395
2396    public PackageManagerService(Context context, Installer installer,
2397            boolean factoryTest, boolean onlyCore) {
2398        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2399        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2400        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2401                SystemClock.uptimeMillis());
2402
2403        if (mSdkVersion <= 0) {
2404            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2405        }
2406
2407        mContext = context;
2408
2409        mPermissionReviewRequired = context.getResources().getBoolean(
2410                R.bool.config_permissionReviewRequired);
2411
2412        mFactoryTest = factoryTest;
2413        mOnlyCore = onlyCore;
2414        mMetrics = new DisplayMetrics();
2415        mSettings = new Settings(mPackages);
2416        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2417                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2418        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2419                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2420        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2421                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2422        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2423                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2424        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2425                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2426        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2427                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2428
2429        String separateProcesses = SystemProperties.get("debug.separate_processes");
2430        if (separateProcesses != null && separateProcesses.length() > 0) {
2431            if ("*".equals(separateProcesses)) {
2432                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2433                mSeparateProcesses = null;
2434                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2435            } else {
2436                mDefParseFlags = 0;
2437                mSeparateProcesses = separateProcesses.split(",");
2438                Slog.w(TAG, "Running with debug.separate_processes: "
2439                        + separateProcesses);
2440            }
2441        } else {
2442            mDefParseFlags = 0;
2443            mSeparateProcesses = null;
2444        }
2445
2446        mInstaller = installer;
2447        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2448                "*dexopt*");
2449        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2450        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2451
2452        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2453                FgThread.get().getLooper());
2454
2455        getDefaultDisplayMetrics(context, mMetrics);
2456
2457        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2458        SystemConfig systemConfig = SystemConfig.getInstance();
2459        mGlobalGids = systemConfig.getGlobalGids();
2460        mSystemPermissions = systemConfig.getSystemPermissions();
2461        mAvailableFeatures = systemConfig.getAvailableFeatures();
2462        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2463
2464        mProtectedPackages = new ProtectedPackages(mContext);
2465
2466        synchronized (mInstallLock) {
2467        // writer
2468        synchronized (mPackages) {
2469            mHandlerThread = new ServiceThread(TAG,
2470                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2471            mHandlerThread.start();
2472            mHandler = new PackageHandler(mHandlerThread.getLooper());
2473            mProcessLoggingHandler = new ProcessLoggingHandler();
2474            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2475
2476            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2477            mInstantAppRegistry = new InstantAppRegistry(this);
2478
2479            File dataDir = Environment.getDataDirectory();
2480            mAppInstallDir = new File(dataDir, "app");
2481            mAppLib32InstallDir = new File(dataDir, "app-lib");
2482            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2483            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2484            sUserManager = new UserManagerService(context, this,
2485                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2486
2487            // Propagate permission configuration in to package manager.
2488            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2489                    = systemConfig.getPermissions();
2490            for (int i=0; i<permConfig.size(); i++) {
2491                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2492                BasePermission bp = mSettings.mPermissions.get(perm.name);
2493                if (bp == null) {
2494                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2495                    mSettings.mPermissions.put(perm.name, bp);
2496                }
2497                if (perm.gids != null) {
2498                    bp.setGids(perm.gids, perm.perUser);
2499                }
2500            }
2501
2502            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2503            final int builtInLibCount = libConfig.size();
2504            for (int i = 0; i < builtInLibCount; i++) {
2505                String name = libConfig.keyAt(i);
2506                String path = libConfig.valueAt(i);
2507                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2508                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2509            }
2510
2511            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2512
2513            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2514            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2515            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2516
2517            // Clean up orphaned packages for which the code path doesn't exist
2518            // and they are an update to a system app - caused by bug/32321269
2519            final int packageSettingCount = mSettings.mPackages.size();
2520            for (int i = packageSettingCount - 1; i >= 0; i--) {
2521                PackageSetting ps = mSettings.mPackages.valueAt(i);
2522                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2523                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2524                    mSettings.mPackages.removeAt(i);
2525                    mSettings.enableSystemPackageLPw(ps.name);
2526                }
2527            }
2528
2529            if (mFirstBoot) {
2530                requestCopyPreoptedFiles();
2531            }
2532
2533            String customResolverActivity = Resources.getSystem().getString(
2534                    R.string.config_customResolverActivity);
2535            if (TextUtils.isEmpty(customResolverActivity)) {
2536                customResolverActivity = null;
2537            } else {
2538                mCustomResolverComponentName = ComponentName.unflattenFromString(
2539                        customResolverActivity);
2540            }
2541
2542            long startTime = SystemClock.uptimeMillis();
2543
2544            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2545                    startTime);
2546
2547            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2548            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2549
2550            if (bootClassPath == null) {
2551                Slog.w(TAG, "No BOOTCLASSPATH found!");
2552            }
2553
2554            if (systemServerClassPath == null) {
2555                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2556            }
2557
2558            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2559
2560            final VersionInfo ver = mSettings.getInternalVersion();
2561            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2562            if (mIsUpgrade) {
2563                logCriticalInfo(Log.INFO,
2564                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2565            }
2566
2567            // when upgrading from pre-M, promote system app permissions from install to runtime
2568            mPromoteSystemApps =
2569                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2570
2571            // When upgrading from pre-N, we need to handle package extraction like first boot,
2572            // as there is no profiling data available.
2573            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2574
2575            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2576
2577            // save off the names of pre-existing system packages prior to scanning; we don't
2578            // want to automatically grant runtime permissions for new system apps
2579            if (mPromoteSystemApps) {
2580                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2581                while (pkgSettingIter.hasNext()) {
2582                    PackageSetting ps = pkgSettingIter.next();
2583                    if (isSystemApp(ps)) {
2584                        mExistingSystemPackages.add(ps.name);
2585                    }
2586                }
2587            }
2588
2589            mCacheDir = preparePackageParserCache(mIsUpgrade);
2590
2591            // Set flag to monitor and not change apk file paths when
2592            // scanning install directories.
2593            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2594
2595            if (mIsUpgrade || mFirstBoot) {
2596                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2597            }
2598
2599            // Collect vendor overlay packages. (Do this before scanning any apps.)
2600            // For security and version matching reason, only consider
2601            // overlay packages if they reside in the right directory.
2602            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2603                    | PackageParser.PARSE_IS_SYSTEM
2604                    | PackageParser.PARSE_IS_SYSTEM_DIR
2605                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2606
2607            mParallelPackageParserCallback.findStaticOverlayPackages();
2608
2609            // Find base frameworks (resource packages without code).
2610            scanDirTracedLI(frameworkDir, mDefParseFlags
2611                    | PackageParser.PARSE_IS_SYSTEM
2612                    | PackageParser.PARSE_IS_SYSTEM_DIR
2613                    | PackageParser.PARSE_IS_PRIVILEGED,
2614                    scanFlags | SCAN_NO_DEX, 0);
2615
2616            // Collected privileged system packages.
2617            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2618            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2619                    | PackageParser.PARSE_IS_SYSTEM
2620                    | PackageParser.PARSE_IS_SYSTEM_DIR
2621                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2622
2623            // Collect ordinary system packages.
2624            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2625            scanDirTracedLI(systemAppDir, mDefParseFlags
2626                    | PackageParser.PARSE_IS_SYSTEM
2627                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2628
2629            // Collect all vendor packages.
2630            File vendorAppDir = new File("/vendor/app");
2631            try {
2632                vendorAppDir = vendorAppDir.getCanonicalFile();
2633            } catch (IOException e) {
2634                // failed to look up canonical path, continue with original one
2635            }
2636            scanDirTracedLI(vendorAppDir, mDefParseFlags
2637                    | PackageParser.PARSE_IS_SYSTEM
2638                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2639
2640            // Collect all OEM packages.
2641            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2642            scanDirTracedLI(oemAppDir, mDefParseFlags
2643                    | PackageParser.PARSE_IS_SYSTEM
2644                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2645
2646            // Prune any system packages that no longer exist.
2647            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2648            // Stub packages must either be replaced with full versions in the /data
2649            // partition or be disabled.
2650            final List<String> stubSystemApps = new ArrayList<>();
2651            if (!mOnlyCore) {
2652                // do this first before mucking with mPackages for the "expecting better" case
2653                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2654                while (pkgIterator.hasNext()) {
2655                    final PackageParser.Package pkg = pkgIterator.next();
2656                    if (pkg.isStub) {
2657                        stubSystemApps.add(pkg.packageName);
2658                    }
2659                }
2660
2661                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2662                while (psit.hasNext()) {
2663                    PackageSetting ps = psit.next();
2664
2665                    /*
2666                     * If this is not a system app, it can't be a
2667                     * disable system app.
2668                     */
2669                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2670                        continue;
2671                    }
2672
2673                    /*
2674                     * If the package is scanned, it's not erased.
2675                     */
2676                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2677                    if (scannedPkg != null) {
2678                        /*
2679                         * If the system app is both scanned and in the
2680                         * disabled packages list, then it must have been
2681                         * added via OTA. Remove it from the currently
2682                         * scanned package so the previously user-installed
2683                         * application can be scanned.
2684                         */
2685                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2686                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2687                                    + ps.name + "; removing system app.  Last known codePath="
2688                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2689                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2690                                    + scannedPkg.mVersionCode);
2691                            removePackageLI(scannedPkg, true);
2692                            mExpectingBetter.put(ps.name, ps.codePath);
2693                        }
2694
2695                        continue;
2696                    }
2697
2698                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2699                        psit.remove();
2700                        logCriticalInfo(Log.WARN, "System package " + ps.name
2701                                + " no longer exists; it's data will be wiped");
2702                        // Actual deletion of code and data will be handled by later
2703                        // reconciliation step
2704                    } else {
2705                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2706                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2707                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2708                        }
2709                    }
2710                }
2711            }
2712
2713            //look for any incomplete package installations
2714            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2715            for (int i = 0; i < deletePkgsList.size(); i++) {
2716                // Actual deletion of code and data will be handled by later
2717                // reconciliation step
2718                final String packageName = deletePkgsList.get(i).name;
2719                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2720                synchronized (mPackages) {
2721                    mSettings.removePackageLPw(packageName);
2722                }
2723            }
2724
2725            //delete tmp files
2726            deleteTempPackageFiles();
2727
2728            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2729
2730            // Remove any shared userIDs that have no associated packages
2731            mSettings.pruneSharedUsersLPw();
2732            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2733            final int systemPackagesCount = mPackages.size();
2734            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2735                    + " ms, packageCount: " + systemPackagesCount
2736                    + " , timePerPackage: "
2737                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2738                    + " , cached: " + cachedSystemApps);
2739            if (mIsUpgrade && systemPackagesCount > 0) {
2740                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2741                        ((int) systemScanTime) / systemPackagesCount);
2742            }
2743            if (!mOnlyCore) {
2744                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2745                        SystemClock.uptimeMillis());
2746                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2747
2748                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2749                        | PackageParser.PARSE_FORWARD_LOCK,
2750                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2751
2752                // Remove disable package settings for updated system apps that were
2753                // removed via an OTA. If the update is no longer present, remove the
2754                // app completely. Otherwise, revoke their system privileges.
2755                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2756                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2757                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2758
2759                    final String msg;
2760                    if (deletedPkg == null) {
2761                        // should have found an update, but, we didn't; remove everything
2762                        msg = "Updated system package " + deletedAppName
2763                                + " no longer exists; removing its data";
2764                        // Actual deletion of code and data will be handled by later
2765                        // reconciliation step
2766                    } else {
2767                        // found an update; revoke system privileges
2768                        msg = "Updated system package + " + deletedAppName
2769                                + " no longer exists; revoking system privileges";
2770
2771                        // Don't do anything if a stub is removed from the system image. If
2772                        // we were to remove the uncompressed version from the /data partition,
2773                        // this is where it'd be done.
2774
2775                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2776                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2777                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2778                    }
2779                    logCriticalInfo(Log.WARN, msg);
2780                }
2781
2782                /*
2783                 * Make sure all system apps that we expected to appear on
2784                 * the userdata partition actually showed up. If they never
2785                 * appeared, crawl back and revive the system version.
2786                 */
2787                for (int i = 0; i < mExpectingBetter.size(); i++) {
2788                    final String packageName = mExpectingBetter.keyAt(i);
2789                    if (!mPackages.containsKey(packageName)) {
2790                        final File scanFile = mExpectingBetter.valueAt(i);
2791
2792                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2793                                + " but never showed up; reverting to system");
2794
2795                        int reparseFlags = mDefParseFlags;
2796                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2797                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2798                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2799                                    | PackageParser.PARSE_IS_PRIVILEGED;
2800                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2801                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2802                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2803                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2804                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2805                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2806                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2807                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2808                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2809                        } else {
2810                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2811                            continue;
2812                        }
2813
2814                        mSettings.enableSystemPackageLPw(packageName);
2815
2816                        try {
2817                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2818                        } catch (PackageManagerException e) {
2819                            Slog.e(TAG, "Failed to parse original system package: "
2820                                    + e.getMessage());
2821                        }
2822                    }
2823                }
2824
2825                // Uncompress and install any stubbed system applications.
2826                // This must be done last to ensure all stubs are replaced or disabled.
2827                decompressSystemApplications(stubSystemApps, scanFlags);
2828
2829                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2830                                - cachedSystemApps;
2831
2832                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2833                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2834                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2835                        + " ms, packageCount: " + dataPackagesCount
2836                        + " , timePerPackage: "
2837                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2838                        + " , cached: " + cachedNonSystemApps);
2839                if (mIsUpgrade && dataPackagesCount > 0) {
2840                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2841                            ((int) dataScanTime) / dataPackagesCount);
2842                }
2843            }
2844            mExpectingBetter.clear();
2845
2846            // Resolve the storage manager.
2847            mStorageManagerPackage = getStorageManagerPackageName();
2848
2849            // Resolve protected action filters. Only the setup wizard is allowed to
2850            // have a high priority filter for these actions.
2851            mSetupWizardPackage = getSetupWizardPackageName();
2852            if (mProtectedFilters.size() > 0) {
2853                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2854                    Slog.i(TAG, "No setup wizard;"
2855                        + " All protected intents capped to priority 0");
2856                }
2857                for (ActivityIntentInfo filter : mProtectedFilters) {
2858                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2859                        if (DEBUG_FILTERS) {
2860                            Slog.i(TAG, "Found setup wizard;"
2861                                + " allow priority " + filter.getPriority() + ";"
2862                                + " package: " + filter.activity.info.packageName
2863                                + " activity: " + filter.activity.className
2864                                + " priority: " + filter.getPriority());
2865                        }
2866                        // skip setup wizard; allow it to keep the high priority filter
2867                        continue;
2868                    }
2869                    if (DEBUG_FILTERS) {
2870                        Slog.i(TAG, "Protected action; cap priority to 0;"
2871                                + " package: " + filter.activity.info.packageName
2872                                + " activity: " + filter.activity.className
2873                                + " origPrio: " + filter.getPriority());
2874                    }
2875                    filter.setPriority(0);
2876                }
2877            }
2878            mDeferProtectedFilters = false;
2879            mProtectedFilters.clear();
2880
2881            // Now that we know all of the shared libraries, update all clients to have
2882            // the correct library paths.
2883            updateAllSharedLibrariesLPw(null);
2884
2885            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2886                // NOTE: We ignore potential failures here during a system scan (like
2887                // the rest of the commands above) because there's precious little we
2888                // can do about it. A settings error is reported, though.
2889                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2890            }
2891
2892            // Now that we know all the packages we are keeping,
2893            // read and update their last usage times.
2894            mPackageUsage.read(mPackages);
2895            mCompilerStats.read();
2896
2897            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2898                    SystemClock.uptimeMillis());
2899            Slog.i(TAG, "Time to scan packages: "
2900                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2901                    + " seconds");
2902
2903            // If the platform SDK has changed since the last time we booted,
2904            // we need to re-grant app permission to catch any new ones that
2905            // appear.  This is really a hack, and means that apps can in some
2906            // cases get permissions that the user didn't initially explicitly
2907            // allow...  it would be nice to have some better way to handle
2908            // this situation.
2909            int updateFlags = UPDATE_PERMISSIONS_ALL;
2910            if (ver.sdkVersion != mSdkVersion) {
2911                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2912                        + mSdkVersion + "; regranting permissions for internal storage");
2913                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2914            }
2915            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2916            ver.sdkVersion = mSdkVersion;
2917
2918            // If this is the first boot or an update from pre-M, and it is a normal
2919            // boot, then we need to initialize the default preferred apps across
2920            // all defined users.
2921            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2922                for (UserInfo user : sUserManager.getUsers(true)) {
2923                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2924                    applyFactoryDefaultBrowserLPw(user.id);
2925                    primeDomainVerificationsLPw(user.id);
2926                }
2927            }
2928
2929            // Prepare storage for system user really early during boot,
2930            // since core system apps like SettingsProvider and SystemUI
2931            // can't wait for user to start
2932            final int storageFlags;
2933            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2934                storageFlags = StorageManager.FLAG_STORAGE_DE;
2935            } else {
2936                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2937            }
2938            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2939                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2940                    true /* onlyCoreApps */);
2941            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2942                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2943                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2944                traceLog.traceBegin("AppDataFixup");
2945                try {
2946                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2947                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2948                } catch (InstallerException e) {
2949                    Slog.w(TAG, "Trouble fixing GIDs", e);
2950                }
2951                traceLog.traceEnd();
2952
2953                traceLog.traceBegin("AppDataPrepare");
2954                if (deferPackages == null || deferPackages.isEmpty()) {
2955                    return;
2956                }
2957                int count = 0;
2958                for (String pkgName : deferPackages) {
2959                    PackageParser.Package pkg = null;
2960                    synchronized (mPackages) {
2961                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2962                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2963                            pkg = ps.pkg;
2964                        }
2965                    }
2966                    if (pkg != null) {
2967                        synchronized (mInstallLock) {
2968                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2969                                    true /* maybeMigrateAppData */);
2970                        }
2971                        count++;
2972                    }
2973                }
2974                traceLog.traceEnd();
2975                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2976            }, "prepareAppData");
2977
2978            // If this is first boot after an OTA, and a normal boot, then
2979            // we need to clear code cache directories.
2980            // Note that we do *not* clear the application profiles. These remain valid
2981            // across OTAs and are used to drive profile verification (post OTA) and
2982            // profile compilation (without waiting to collect a fresh set of profiles).
2983            if (mIsUpgrade && !onlyCore) {
2984                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2985                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2986                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2987                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2988                        // No apps are running this early, so no need to freeze
2989                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2990                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2991                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2992                    }
2993                }
2994                ver.fingerprint = Build.FINGERPRINT;
2995            }
2996
2997            checkDefaultBrowser();
2998
2999            // clear only after permissions and other defaults have been updated
3000            mExistingSystemPackages.clear();
3001            mPromoteSystemApps = false;
3002
3003            // All the changes are done during package scanning.
3004            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3005
3006            // can downgrade to reader
3007            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3008            mSettings.writeLPr();
3009            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3010            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3011                    SystemClock.uptimeMillis());
3012
3013            if (!mOnlyCore) {
3014                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3015                mRequiredInstallerPackage = getRequiredInstallerLPr();
3016                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3017                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3018                if (mIntentFilterVerifierComponent != null) {
3019                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3020                            mIntentFilterVerifierComponent);
3021                } else {
3022                    mIntentFilterVerifier = null;
3023                }
3024                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3025                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3026                        SharedLibraryInfo.VERSION_UNDEFINED);
3027                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3028                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3029                        SharedLibraryInfo.VERSION_UNDEFINED);
3030            } else {
3031                mRequiredVerifierPackage = null;
3032                mRequiredInstallerPackage = null;
3033                mRequiredUninstallerPackage = null;
3034                mIntentFilterVerifierComponent = null;
3035                mIntentFilterVerifier = null;
3036                mServicesSystemSharedLibraryPackageName = null;
3037                mSharedSystemSharedLibraryPackageName = null;
3038            }
3039
3040            mInstallerService = new PackageInstallerService(context, this);
3041            final Pair<ComponentName, String> instantAppResolverComponent =
3042                    getInstantAppResolverLPr();
3043            if (instantAppResolverComponent != null) {
3044                if (DEBUG_EPHEMERAL) {
3045                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3046                }
3047                mInstantAppResolverConnection = new EphemeralResolverConnection(
3048                        mContext, instantAppResolverComponent.first,
3049                        instantAppResolverComponent.second);
3050                mInstantAppResolverSettingsComponent =
3051                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3052            } else {
3053                mInstantAppResolverConnection = null;
3054                mInstantAppResolverSettingsComponent = null;
3055            }
3056            updateInstantAppInstallerLocked(null);
3057
3058            // Read and update the usage of dex files.
3059            // Do this at the end of PM init so that all the packages have their
3060            // data directory reconciled.
3061            // At this point we know the code paths of the packages, so we can validate
3062            // the disk file and build the internal cache.
3063            // The usage file is expected to be small so loading and verifying it
3064            // should take a fairly small time compare to the other activities (e.g. package
3065            // scanning).
3066            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3067            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3068            for (int userId : currentUserIds) {
3069                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3070            }
3071            mDexManager.load(userPackages);
3072            if (mIsUpgrade) {
3073                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3074                        (int) (SystemClock.uptimeMillis() - startTime));
3075            }
3076        } // synchronized (mPackages)
3077        } // synchronized (mInstallLock)
3078
3079        // Now after opening every single application zip, make sure they
3080        // are all flushed.  Not really needed, but keeps things nice and
3081        // tidy.
3082        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3083        Runtime.getRuntime().gc();
3084        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3085
3086        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3087        FallbackCategoryProvider.loadFallbacks();
3088        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3089
3090        // The initial scanning above does many calls into installd while
3091        // holding the mPackages lock, but we're mostly interested in yelling
3092        // once we have a booted system.
3093        mInstaller.setWarnIfHeld(mPackages);
3094
3095        // Expose private service for system components to use.
3096        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3097        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3098    }
3099
3100    /**
3101     * Uncompress and install stub applications.
3102     * <p>In order to save space on the system partition, some applications are shipped in a
3103     * compressed form. In addition the compressed bits for the full application, the
3104     * system image contains a tiny stub comprised of only the Android manifest.
3105     * <p>During the first boot, attempt to uncompress and install the full application. If
3106     * the application can't be installed for any reason, disable the stub and prevent
3107     * uncompressing the full application during future boots.
3108     * <p>In order to forcefully attempt an installation of a full application, go to app
3109     * settings and enable the application.
3110     */
3111    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3112        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3113            final String pkgName = stubSystemApps.get(i);
3114            // skip if the system package is already disabled
3115            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3116                stubSystemApps.remove(i);
3117                continue;
3118            }
3119            // skip if the package isn't installed (?!); this should never happen
3120            final PackageParser.Package pkg = mPackages.get(pkgName);
3121            if (pkg == null) {
3122                stubSystemApps.remove(i);
3123                continue;
3124            }
3125            // skip if the package has been disabled by the user
3126            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3127            if (ps != null) {
3128                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3129                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3130                    stubSystemApps.remove(i);
3131                    continue;
3132                }
3133            }
3134
3135            if (DEBUG_COMPRESSION) {
3136                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3137            }
3138
3139            // uncompress the binary to its eventual destination on /data
3140            final File scanFile = decompressPackage(pkg);
3141            if (scanFile == null) {
3142                continue;
3143            }
3144
3145            // install the package to replace the stub on /system
3146            try {
3147                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3148                removePackageLI(pkg, true /*chatty*/);
3149                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3150                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3151                        UserHandle.USER_SYSTEM, "android");
3152                stubSystemApps.remove(i);
3153                continue;
3154            } catch (PackageManagerException e) {
3155                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3156            }
3157
3158            // any failed attempt to install the package will be cleaned up later
3159        }
3160
3161        // disable any stub still left; these failed to install the full application
3162        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3163            final String pkgName = stubSystemApps.get(i);
3164            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3165            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3166                    UserHandle.USER_SYSTEM, "android");
3167            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3168        }
3169    }
3170
3171    private int decompressFile(File srcFile, File dstFile) throws ErrnoException {
3172        if (DEBUG_COMPRESSION) {
3173            Slog.i(TAG, "Decompress file"
3174                    + "; src: " + srcFile.getAbsolutePath()
3175                    + ", dst: " + dstFile.getAbsolutePath());
3176        }
3177        try (
3178                InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile));
3179                OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/);
3180        ) {
3181            Streams.copy(fileIn, fileOut);
3182            Os.chmod(dstFile.getAbsolutePath(), 0644);
3183            return PackageManager.INSTALL_SUCCEEDED;
3184        } catch (IOException e) {
3185            logCriticalInfo(Log.ERROR, "Failed to decompress file"
3186                    + "; src: " + srcFile.getAbsolutePath()
3187                    + ", dst: " + dstFile.getAbsolutePath());
3188        }
3189        return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3190    }
3191
3192    private File[] getCompressedFiles(String codePath) {
3193        return new File(codePath).listFiles(new FilenameFilter() {
3194            @Override
3195            public boolean accept(File dir, String name) {
3196                return name.toLowerCase().endsWith(COMPRESSED_EXTENSION);
3197            }
3198        });
3199    }
3200
3201    private boolean compressedFileExists(String codePath) {
3202        final File[] compressedFiles = getCompressedFiles(codePath);
3203        return compressedFiles != null && compressedFiles.length > 0;
3204    }
3205
3206    /**
3207     * Decompresses the given package on the system image onto
3208     * the /data partition.
3209     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3210     */
3211    private File decompressPackage(PackageParser.Package pkg) {
3212        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3213        if (compressedFiles == null || compressedFiles.length == 0) {
3214            if (DEBUG_COMPRESSION) {
3215                Slog.i(TAG, "No files to decompress");
3216            }
3217            return null;
3218        }
3219        final File dstCodePath =
3220                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3221        int ret = PackageManager.INSTALL_SUCCEEDED;
3222        try {
3223            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3224            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3225            for (File srcFile : compressedFiles) {
3226                final String srcFileName = srcFile.getName();
3227                final String dstFileName = srcFileName.substring(
3228                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3229                final File dstFile = new File(dstCodePath, dstFileName);
3230                ret = decompressFile(srcFile, dstFile);
3231                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3232                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3233                            + "; pkg: " + pkg.packageName
3234                            + ", file: " + dstFileName);
3235                    break;
3236                }
3237            }
3238        } catch (ErrnoException e) {
3239            logCriticalInfo(Log.ERROR, "Failed to decompress"
3240                    + "; pkg: " + pkg.packageName
3241                    + ", err: " + e.errno);
3242        }
3243        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3244            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3245            NativeLibraryHelper.Handle handle = null;
3246            try {
3247                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3248                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3249                        null /*abiOverride*/);
3250            } catch (IOException e) {
3251                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3252                        + "; pkg: " + pkg.packageName);
3253                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3254            } finally {
3255                IoUtils.closeQuietly(handle);
3256            }
3257        }
3258        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3259            if (dstCodePath == null || !dstCodePath.exists()) {
3260                return null;
3261            }
3262            removeCodePathLI(dstCodePath);
3263            return null;
3264        }
3265        return dstCodePath;
3266    }
3267
3268    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3269        // we're only interested in updating the installer appliction when 1) it's not
3270        // already set or 2) the modified package is the installer
3271        if (mInstantAppInstallerActivity != null
3272                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3273                        .equals(modifiedPackage)) {
3274            return;
3275        }
3276        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3277    }
3278
3279    private static File preparePackageParserCache(boolean isUpgrade) {
3280        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3281            return null;
3282        }
3283
3284        // Disable package parsing on eng builds to allow for faster incremental development.
3285        if (Build.IS_ENG) {
3286            return null;
3287        }
3288
3289        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3290            Slog.i(TAG, "Disabling package parser cache due to system property.");
3291            return null;
3292        }
3293
3294        // The base directory for the package parser cache lives under /data/system/.
3295        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3296                "package_cache");
3297        if (cacheBaseDir == null) {
3298            return null;
3299        }
3300
3301        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3302        // This also serves to "GC" unused entries when the package cache version changes (which
3303        // can only happen during upgrades).
3304        if (isUpgrade) {
3305            FileUtils.deleteContents(cacheBaseDir);
3306        }
3307
3308
3309        // Return the versioned package cache directory. This is something like
3310        // "/data/system/package_cache/1"
3311        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3312
3313        // The following is a workaround to aid development on non-numbered userdebug
3314        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3315        // the system partition is newer.
3316        //
3317        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3318        // that starts with "eng." to signify that this is an engineering build and not
3319        // destined for release.
3320        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3321            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3322
3323            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3324            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3325            // in general and should not be used for production changes. In this specific case,
3326            // we know that they will work.
3327            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3328            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3329                FileUtils.deleteContents(cacheBaseDir);
3330                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3331            }
3332        }
3333
3334        return cacheDir;
3335    }
3336
3337    @Override
3338    public boolean isFirstBoot() {
3339        // allow instant applications
3340        return mFirstBoot;
3341    }
3342
3343    @Override
3344    public boolean isOnlyCoreApps() {
3345        // allow instant applications
3346        return mOnlyCore;
3347    }
3348
3349    @Override
3350    public boolean isUpgrade() {
3351        // allow instant applications
3352        return mIsUpgrade;
3353    }
3354
3355    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3356        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3357
3358        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3359                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3360                UserHandle.USER_SYSTEM);
3361        if (matches.size() == 1) {
3362            return matches.get(0).getComponentInfo().packageName;
3363        } else if (matches.size() == 0) {
3364            Log.e(TAG, "There should probably be a verifier, but, none were found");
3365            return null;
3366        }
3367        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3368    }
3369
3370    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3371        synchronized (mPackages) {
3372            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3373            if (libraryEntry == null) {
3374                throw new IllegalStateException("Missing required shared library:" + name);
3375            }
3376            return libraryEntry.apk;
3377        }
3378    }
3379
3380    private @NonNull String getRequiredInstallerLPr() {
3381        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3382        intent.addCategory(Intent.CATEGORY_DEFAULT);
3383        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3384
3385        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3386                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3387                UserHandle.USER_SYSTEM);
3388        if (matches.size() == 1) {
3389            ResolveInfo resolveInfo = matches.get(0);
3390            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3391                throw new RuntimeException("The installer must be a privileged app");
3392            }
3393            return matches.get(0).getComponentInfo().packageName;
3394        } else {
3395            throw new RuntimeException("There must be exactly one installer; found " + matches);
3396        }
3397    }
3398
3399    private @NonNull String getRequiredUninstallerLPr() {
3400        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3401        intent.addCategory(Intent.CATEGORY_DEFAULT);
3402        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3403
3404        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3405                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3406                UserHandle.USER_SYSTEM);
3407        if (resolveInfo == null ||
3408                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3409            throw new RuntimeException("There must be exactly one uninstaller; found "
3410                    + resolveInfo);
3411        }
3412        return resolveInfo.getComponentInfo().packageName;
3413    }
3414
3415    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3416        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3417
3418        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3419                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3420                UserHandle.USER_SYSTEM);
3421        ResolveInfo best = null;
3422        final int N = matches.size();
3423        for (int i = 0; i < N; i++) {
3424            final ResolveInfo cur = matches.get(i);
3425            final String packageName = cur.getComponentInfo().packageName;
3426            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3427                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3428                continue;
3429            }
3430
3431            if (best == null || cur.priority > best.priority) {
3432                best = cur;
3433            }
3434        }
3435
3436        if (best != null) {
3437            return best.getComponentInfo().getComponentName();
3438        }
3439        Slog.w(TAG, "Intent filter verifier not found");
3440        return null;
3441    }
3442
3443    @Override
3444    public @Nullable ComponentName getInstantAppResolverComponent() {
3445        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3446            return null;
3447        }
3448        synchronized (mPackages) {
3449            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3450            if (instantAppResolver == null) {
3451                return null;
3452            }
3453            return instantAppResolver.first;
3454        }
3455    }
3456
3457    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3458        final String[] packageArray =
3459                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3460        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3461            if (DEBUG_EPHEMERAL) {
3462                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3463            }
3464            return null;
3465        }
3466
3467        final int callingUid = Binder.getCallingUid();
3468        final int resolveFlags =
3469                MATCH_DIRECT_BOOT_AWARE
3470                | MATCH_DIRECT_BOOT_UNAWARE
3471                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3472        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3473        final Intent resolverIntent = new Intent(actionName);
3474        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3475                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3476        // temporarily look for the old action
3477        if (resolvers.size() == 0) {
3478            if (DEBUG_EPHEMERAL) {
3479                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3480            }
3481            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3482            resolverIntent.setAction(actionName);
3483            resolvers = queryIntentServicesInternal(resolverIntent, null,
3484                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3485        }
3486        final int N = resolvers.size();
3487        if (N == 0) {
3488            if (DEBUG_EPHEMERAL) {
3489                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3490            }
3491            return null;
3492        }
3493
3494        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3495        for (int i = 0; i < N; i++) {
3496            final ResolveInfo info = resolvers.get(i);
3497
3498            if (info.serviceInfo == null) {
3499                continue;
3500            }
3501
3502            final String packageName = info.serviceInfo.packageName;
3503            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3504                if (DEBUG_EPHEMERAL) {
3505                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3506                            + " pkg: " + packageName + ", info:" + info);
3507                }
3508                continue;
3509            }
3510
3511            if (DEBUG_EPHEMERAL) {
3512                Slog.v(TAG, "Ephemeral resolver found;"
3513                        + " pkg: " + packageName + ", info:" + info);
3514            }
3515            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3516        }
3517        if (DEBUG_EPHEMERAL) {
3518            Slog.v(TAG, "Ephemeral resolver NOT found");
3519        }
3520        return null;
3521    }
3522
3523    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3524        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3525        intent.addCategory(Intent.CATEGORY_DEFAULT);
3526        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3527
3528        final int resolveFlags =
3529                MATCH_DIRECT_BOOT_AWARE
3530                | MATCH_DIRECT_BOOT_UNAWARE
3531                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3532        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3533                resolveFlags, UserHandle.USER_SYSTEM);
3534        // temporarily look for the old action
3535        if (matches.isEmpty()) {
3536            if (DEBUG_EPHEMERAL) {
3537                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3538            }
3539            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3540            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3541                    resolveFlags, UserHandle.USER_SYSTEM);
3542        }
3543        Iterator<ResolveInfo> iter = matches.iterator();
3544        while (iter.hasNext()) {
3545            final ResolveInfo rInfo = iter.next();
3546            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3547            if (ps != null) {
3548                final PermissionsState permissionsState = ps.getPermissionsState();
3549                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3550                    continue;
3551                }
3552            }
3553            iter.remove();
3554        }
3555        if (matches.size() == 0) {
3556            return null;
3557        } else if (matches.size() == 1) {
3558            return (ActivityInfo) matches.get(0).getComponentInfo();
3559        } else {
3560            throw new RuntimeException(
3561                    "There must be at most one ephemeral installer; found " + matches);
3562        }
3563    }
3564
3565    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3566            @NonNull ComponentName resolver) {
3567        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3568                .addCategory(Intent.CATEGORY_DEFAULT)
3569                .setPackage(resolver.getPackageName());
3570        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3571        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3572                UserHandle.USER_SYSTEM);
3573        // temporarily look for the old action
3574        if (matches.isEmpty()) {
3575            if (DEBUG_EPHEMERAL) {
3576                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3577            }
3578            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3579            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3580                    UserHandle.USER_SYSTEM);
3581        }
3582        if (matches.isEmpty()) {
3583            return null;
3584        }
3585        return matches.get(0).getComponentInfo().getComponentName();
3586    }
3587
3588    private void primeDomainVerificationsLPw(int userId) {
3589        if (DEBUG_DOMAIN_VERIFICATION) {
3590            Slog.d(TAG, "Priming domain verifications in user " + userId);
3591        }
3592
3593        SystemConfig systemConfig = SystemConfig.getInstance();
3594        ArraySet<String> packages = systemConfig.getLinkedApps();
3595
3596        for (String packageName : packages) {
3597            PackageParser.Package pkg = mPackages.get(packageName);
3598            if (pkg != null) {
3599                if (!pkg.isSystemApp()) {
3600                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3601                    continue;
3602                }
3603
3604                ArraySet<String> domains = null;
3605                for (PackageParser.Activity a : pkg.activities) {
3606                    for (ActivityIntentInfo filter : a.intents) {
3607                        if (hasValidDomains(filter)) {
3608                            if (domains == null) {
3609                                domains = new ArraySet<String>();
3610                            }
3611                            domains.addAll(filter.getHostsList());
3612                        }
3613                    }
3614                }
3615
3616                if (domains != null && domains.size() > 0) {
3617                    if (DEBUG_DOMAIN_VERIFICATION) {
3618                        Slog.v(TAG, "      + " + packageName);
3619                    }
3620                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3621                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3622                    // and then 'always' in the per-user state actually used for intent resolution.
3623                    final IntentFilterVerificationInfo ivi;
3624                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3625                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3626                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3627                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3628                } else {
3629                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3630                            + "' does not handle web links");
3631                }
3632            } else {
3633                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3634            }
3635        }
3636
3637        scheduleWritePackageRestrictionsLocked(userId);
3638        scheduleWriteSettingsLocked();
3639    }
3640
3641    private void applyFactoryDefaultBrowserLPw(int userId) {
3642        // The default browser app's package name is stored in a string resource,
3643        // with a product-specific overlay used for vendor customization.
3644        String browserPkg = mContext.getResources().getString(
3645                com.android.internal.R.string.default_browser);
3646        if (!TextUtils.isEmpty(browserPkg)) {
3647            // non-empty string => required to be a known package
3648            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3649            if (ps == null) {
3650                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3651                browserPkg = null;
3652            } else {
3653                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3654            }
3655        }
3656
3657        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3658        // default.  If there's more than one, just leave everything alone.
3659        if (browserPkg == null) {
3660            calculateDefaultBrowserLPw(userId);
3661        }
3662    }
3663
3664    private void calculateDefaultBrowserLPw(int userId) {
3665        List<String> allBrowsers = resolveAllBrowserApps(userId);
3666        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3667        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3668    }
3669
3670    private List<String> resolveAllBrowserApps(int userId) {
3671        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3672        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3673                PackageManager.MATCH_ALL, userId);
3674
3675        final int count = list.size();
3676        List<String> result = new ArrayList<String>(count);
3677        for (int i=0; i<count; i++) {
3678            ResolveInfo info = list.get(i);
3679            if (info.activityInfo == null
3680                    || !info.handleAllWebDataURI
3681                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3682                    || result.contains(info.activityInfo.packageName)) {
3683                continue;
3684            }
3685            result.add(info.activityInfo.packageName);
3686        }
3687
3688        return result;
3689    }
3690
3691    private boolean packageIsBrowser(String packageName, int userId) {
3692        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3693                PackageManager.MATCH_ALL, userId);
3694        final int N = list.size();
3695        for (int i = 0; i < N; i++) {
3696            ResolveInfo info = list.get(i);
3697            if (packageName.equals(info.activityInfo.packageName)) {
3698                return true;
3699            }
3700        }
3701        return false;
3702    }
3703
3704    private void checkDefaultBrowser() {
3705        final int myUserId = UserHandle.myUserId();
3706        final String packageName = getDefaultBrowserPackageName(myUserId);
3707        if (packageName != null) {
3708            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3709            if (info == null) {
3710                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3711                synchronized (mPackages) {
3712                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3713                }
3714            }
3715        }
3716    }
3717
3718    @Override
3719    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3720            throws RemoteException {
3721        try {
3722            return super.onTransact(code, data, reply, flags);
3723        } catch (RuntimeException e) {
3724            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3725                Slog.wtf(TAG, "Package Manager Crash", e);
3726            }
3727            throw e;
3728        }
3729    }
3730
3731    static int[] appendInts(int[] cur, int[] add) {
3732        if (add == null) return cur;
3733        if (cur == null) return add;
3734        final int N = add.length;
3735        for (int i=0; i<N; i++) {
3736            cur = appendInt(cur, add[i]);
3737        }
3738        return cur;
3739    }
3740
3741    /**
3742     * Returns whether or not a full application can see an instant application.
3743     * <p>
3744     * Currently, there are three cases in which this can occur:
3745     * <ol>
3746     * <li>The calling application is a "special" process. The special
3747     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3748     *     and {@code 0}</li>
3749     * <li>The calling application has the permission
3750     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3751     * <li>The calling application is the default launcher on the
3752     *     system partition.</li>
3753     * </ol>
3754     */
3755    private boolean canViewInstantApps(int callingUid, int userId) {
3756        if (callingUid == Process.SYSTEM_UID
3757                || callingUid == Process.SHELL_UID
3758                || callingUid == Process.ROOT_UID) {
3759            return true;
3760        }
3761        if (mContext.checkCallingOrSelfPermission(
3762                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3763            return true;
3764        }
3765        if (mContext.checkCallingOrSelfPermission(
3766                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3767            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3768            if (homeComponent != null
3769                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3770                return true;
3771            }
3772        }
3773        return false;
3774    }
3775
3776    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3777        if (!sUserManager.exists(userId)) return null;
3778        if (ps == null) {
3779            return null;
3780        }
3781        PackageParser.Package p = ps.pkg;
3782        if (p == null) {
3783            return null;
3784        }
3785        final int callingUid = Binder.getCallingUid();
3786        // Filter out ephemeral app metadata:
3787        //   * The system/shell/root can see metadata for any app
3788        //   * An installed app can see metadata for 1) other installed apps
3789        //     and 2) ephemeral apps that have explicitly interacted with it
3790        //   * Ephemeral apps can only see their own data and exposed installed apps
3791        //   * Holding a signature permission allows seeing instant apps
3792        if (filterAppAccessLPr(ps, callingUid, userId)) {
3793            return null;
3794        }
3795
3796        final PermissionsState permissionsState = ps.getPermissionsState();
3797
3798        // Compute GIDs only if requested
3799        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3800                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3801        // Compute granted permissions only if package has requested permissions
3802        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3803                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3804        final PackageUserState state = ps.readUserState(userId);
3805
3806        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3807                && ps.isSystem()) {
3808            flags |= MATCH_ANY_USER;
3809        }
3810
3811        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3812                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3813
3814        if (packageInfo == null) {
3815            return null;
3816        }
3817
3818        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3819                resolveExternalPackageNameLPr(p);
3820
3821        return packageInfo;
3822    }
3823
3824    @Override
3825    public void checkPackageStartable(String packageName, int userId) {
3826        final int callingUid = Binder.getCallingUid();
3827        if (getInstantAppPackageName(callingUid) != null) {
3828            throw new SecurityException("Instant applications don't have access to this method");
3829        }
3830        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3831        synchronized (mPackages) {
3832            final PackageSetting ps = mSettings.mPackages.get(packageName);
3833            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3834                throw new SecurityException("Package " + packageName + " was not found!");
3835            }
3836
3837            if (!ps.getInstalled(userId)) {
3838                throw new SecurityException(
3839                        "Package " + packageName + " was not installed for user " + userId + "!");
3840            }
3841
3842            if (mSafeMode && !ps.isSystem()) {
3843                throw new SecurityException("Package " + packageName + " not a system app!");
3844            }
3845
3846            if (mFrozenPackages.contains(packageName)) {
3847                throw new SecurityException("Package " + packageName + " is currently frozen!");
3848            }
3849
3850            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3851                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3852                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3853            }
3854        }
3855    }
3856
3857    @Override
3858    public boolean isPackageAvailable(String packageName, int userId) {
3859        if (!sUserManager.exists(userId)) return false;
3860        final int callingUid = Binder.getCallingUid();
3861        enforceCrossUserPermission(callingUid, userId,
3862                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3863        synchronized (mPackages) {
3864            PackageParser.Package p = mPackages.get(packageName);
3865            if (p != null) {
3866                final PackageSetting ps = (PackageSetting) p.mExtras;
3867                if (filterAppAccessLPr(ps, callingUid, userId)) {
3868                    return false;
3869                }
3870                if (ps != null) {
3871                    final PackageUserState state = ps.readUserState(userId);
3872                    if (state != null) {
3873                        return PackageParser.isAvailable(state);
3874                    }
3875                }
3876            }
3877        }
3878        return false;
3879    }
3880
3881    @Override
3882    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3883        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3884                flags, Binder.getCallingUid(), userId);
3885    }
3886
3887    @Override
3888    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3889            int flags, int userId) {
3890        return getPackageInfoInternal(versionedPackage.getPackageName(),
3891                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3892    }
3893
3894    /**
3895     * Important: The provided filterCallingUid is used exclusively to filter out packages
3896     * that can be seen based on user state. It's typically the original caller uid prior
3897     * to clearing. Because it can only be provided by trusted code, it's value can be
3898     * trusted and will be used as-is; unlike userId which will be validated by this method.
3899     */
3900    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3901            int flags, int filterCallingUid, int userId) {
3902        if (!sUserManager.exists(userId)) return null;
3903        flags = updateFlagsForPackage(flags, userId, packageName);
3904        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3905                false /* requireFullPermission */, false /* checkShell */, "get package info");
3906
3907        // reader
3908        synchronized (mPackages) {
3909            // Normalize package name to handle renamed packages and static libs
3910            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3911
3912            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3913            if (matchFactoryOnly) {
3914                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3915                if (ps != null) {
3916                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3917                        return null;
3918                    }
3919                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3920                        return null;
3921                    }
3922                    return generatePackageInfo(ps, flags, userId);
3923                }
3924            }
3925
3926            PackageParser.Package p = mPackages.get(packageName);
3927            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3928                return null;
3929            }
3930            if (DEBUG_PACKAGE_INFO)
3931                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3932            if (p != null) {
3933                final PackageSetting ps = (PackageSetting) p.mExtras;
3934                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3935                    return null;
3936                }
3937                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3938                    return null;
3939                }
3940                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3941            }
3942            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3943                final PackageSetting ps = mSettings.mPackages.get(packageName);
3944                if (ps == null) return null;
3945                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3946                    return null;
3947                }
3948                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3949                    return null;
3950                }
3951                return generatePackageInfo(ps, flags, userId);
3952            }
3953        }
3954        return null;
3955    }
3956
3957    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3958        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3959            return true;
3960        }
3961        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3962            return true;
3963        }
3964        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3965            return true;
3966        }
3967        return false;
3968    }
3969
3970    private boolean isComponentVisibleToInstantApp(
3971            @Nullable ComponentName component, @ComponentType int type) {
3972        if (type == TYPE_ACTIVITY) {
3973            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3974            return activity != null
3975                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3976                    : false;
3977        } else if (type == TYPE_RECEIVER) {
3978            final PackageParser.Activity activity = mReceivers.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_SERVICE) {
3983            final PackageParser.Service service = mServices.mServices.get(component);
3984            return service != null
3985                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3986                    : false;
3987        } else if (type == TYPE_PROVIDER) {
3988            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3989            return provider != null
3990                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3991                    : false;
3992        } else if (type == TYPE_UNKNOWN) {
3993            return isComponentVisibleToInstantApp(component);
3994        }
3995        return false;
3996    }
3997
3998    /**
3999     * Returns whether or not access to the application should be filtered.
4000     * <p>
4001     * Access may be limited based upon whether the calling or target applications
4002     * are instant applications.
4003     *
4004     * @see #canAccessInstantApps(int)
4005     */
4006    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4007            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4008        // if we're in an isolated process, get the real calling UID
4009        if (Process.isIsolated(callingUid)) {
4010            callingUid = mIsolatedOwners.get(callingUid);
4011        }
4012        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4013        final boolean callerIsInstantApp = instantAppPkgName != null;
4014        if (ps == null) {
4015            if (callerIsInstantApp) {
4016                // pretend the application exists, but, needs to be filtered
4017                return true;
4018            }
4019            return false;
4020        }
4021        // if the target and caller are the same application, don't filter
4022        if (isCallerSameApp(ps.name, callingUid)) {
4023            return false;
4024        }
4025        if (callerIsInstantApp) {
4026            // request for a specific component; if it hasn't been explicitly exposed, filter
4027            if (component != null) {
4028                return !isComponentVisibleToInstantApp(component, componentType);
4029            }
4030            // request for application; if no components have been explicitly exposed, filter
4031            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4032        }
4033        if (ps.getInstantApp(userId)) {
4034            // caller can see all components of all instant applications, don't filter
4035            if (canViewInstantApps(callingUid, userId)) {
4036                return false;
4037            }
4038            // request for a specific instant application component, filter
4039            if (component != null) {
4040                return true;
4041            }
4042            // request for an instant application; if the caller hasn't been granted access, filter
4043            return !mInstantAppRegistry.isInstantAccessGranted(
4044                    userId, UserHandle.getAppId(callingUid), ps.appId);
4045        }
4046        return false;
4047    }
4048
4049    /**
4050     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4051     */
4052    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4053        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4054    }
4055
4056    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4057            int flags) {
4058        // Callers can access only the libs they depend on, otherwise they need to explicitly
4059        // ask for the shared libraries given the caller is allowed to access all static libs.
4060        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4061            // System/shell/root get to see all static libs
4062            final int appId = UserHandle.getAppId(uid);
4063            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4064                    || appId == Process.ROOT_UID) {
4065                return false;
4066            }
4067        }
4068
4069        // No package means no static lib as it is always on internal storage
4070        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4071            return false;
4072        }
4073
4074        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4075                ps.pkg.staticSharedLibVersion);
4076        if (libEntry == null) {
4077            return false;
4078        }
4079
4080        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4081        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4082        if (uidPackageNames == null) {
4083            return true;
4084        }
4085
4086        for (String uidPackageName : uidPackageNames) {
4087            if (ps.name.equals(uidPackageName)) {
4088                return false;
4089            }
4090            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4091            if (uidPs != null) {
4092                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4093                        libEntry.info.getName());
4094                if (index < 0) {
4095                    continue;
4096                }
4097                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
4098                    return false;
4099                }
4100            }
4101        }
4102        return true;
4103    }
4104
4105    @Override
4106    public String[] currentToCanonicalPackageNames(String[] names) {
4107        final int callingUid = Binder.getCallingUid();
4108        if (getInstantAppPackageName(callingUid) != null) {
4109            return names;
4110        }
4111        final String[] out = new String[names.length];
4112        // reader
4113        synchronized (mPackages) {
4114            final int callingUserId = UserHandle.getUserId(callingUid);
4115            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4116            for (int i=names.length-1; i>=0; i--) {
4117                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4118                boolean translateName = false;
4119                if (ps != null && ps.realName != null) {
4120                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4121                    translateName = !targetIsInstantApp
4122                            || canViewInstantApps
4123                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4124                                    UserHandle.getAppId(callingUid), ps.appId);
4125                }
4126                out[i] = translateName ? ps.realName : names[i];
4127            }
4128        }
4129        return out;
4130    }
4131
4132    @Override
4133    public String[] canonicalToCurrentPackageNames(String[] names) {
4134        final int callingUid = Binder.getCallingUid();
4135        if (getInstantAppPackageName(callingUid) != null) {
4136            return names;
4137        }
4138        final String[] out = new String[names.length];
4139        // reader
4140        synchronized (mPackages) {
4141            final int callingUserId = UserHandle.getUserId(callingUid);
4142            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4143            for (int i=names.length-1; i>=0; i--) {
4144                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4145                boolean translateName = false;
4146                if (cur != null) {
4147                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4148                    final boolean targetIsInstantApp =
4149                            ps != null && ps.getInstantApp(callingUserId);
4150                    translateName = !targetIsInstantApp
4151                            || canViewInstantApps
4152                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4153                                    UserHandle.getAppId(callingUid), ps.appId);
4154                }
4155                out[i] = translateName ? cur : names[i];
4156            }
4157        }
4158        return out;
4159    }
4160
4161    @Override
4162    public int getPackageUid(String packageName, int flags, int userId) {
4163        if (!sUserManager.exists(userId)) return -1;
4164        final int callingUid = Binder.getCallingUid();
4165        flags = updateFlagsForPackage(flags, userId, packageName);
4166        enforceCrossUserPermission(callingUid, userId,
4167                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4168
4169        // reader
4170        synchronized (mPackages) {
4171            final PackageParser.Package p = mPackages.get(packageName);
4172            if (p != null && p.isMatch(flags)) {
4173                PackageSetting ps = (PackageSetting) p.mExtras;
4174                if (filterAppAccessLPr(ps, callingUid, userId)) {
4175                    return -1;
4176                }
4177                return UserHandle.getUid(userId, p.applicationInfo.uid);
4178            }
4179            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4180                final PackageSetting ps = mSettings.mPackages.get(packageName);
4181                if (ps != null && ps.isMatch(flags)
4182                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4183                    return UserHandle.getUid(userId, ps.appId);
4184                }
4185            }
4186        }
4187
4188        return -1;
4189    }
4190
4191    @Override
4192    public int[] getPackageGids(String packageName, int flags, int userId) {
4193        if (!sUserManager.exists(userId)) return null;
4194        final int callingUid = Binder.getCallingUid();
4195        flags = updateFlagsForPackage(flags, userId, packageName);
4196        enforceCrossUserPermission(callingUid, userId,
4197                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4198
4199        // reader
4200        synchronized (mPackages) {
4201            final PackageParser.Package p = mPackages.get(packageName);
4202            if (p != null && p.isMatch(flags)) {
4203                PackageSetting ps = (PackageSetting) p.mExtras;
4204                if (filterAppAccessLPr(ps, callingUid, userId)) {
4205                    return null;
4206                }
4207                // TODO: Shouldn't this be checking for package installed state for userId and
4208                // return null?
4209                return ps.getPermissionsState().computeGids(userId);
4210            }
4211            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4212                final PackageSetting ps = mSettings.mPackages.get(packageName);
4213                if (ps != null && ps.isMatch(flags)
4214                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4215                    return ps.getPermissionsState().computeGids(userId);
4216                }
4217            }
4218        }
4219
4220        return null;
4221    }
4222
4223    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
4224        if (bp.perm != null) {
4225            return PackageParser.generatePermissionInfo(bp.perm, flags);
4226        }
4227        PermissionInfo pi = new PermissionInfo();
4228        pi.name = bp.name;
4229        pi.packageName = bp.sourcePackage;
4230        pi.nonLocalizedLabel = bp.name;
4231        pi.protectionLevel = bp.protectionLevel;
4232        return pi;
4233    }
4234
4235    @Override
4236    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4237        final int callingUid = Binder.getCallingUid();
4238        if (getInstantAppPackageName(callingUid) != null) {
4239            return null;
4240        }
4241        // reader
4242        synchronized (mPackages) {
4243            final BasePermission p = mSettings.mPermissions.get(name);
4244            if (p == null) {
4245                return null;
4246            }
4247            // If the caller is an app that targets pre 26 SDK drop protection flags.
4248            final PermissionInfo permissionInfo = generatePermissionInfo(p, flags);
4249            if (permissionInfo != null) {
4250                permissionInfo.protectionLevel = adjustPermissionProtectionFlagsLPr(
4251                        permissionInfo.protectionLevel, packageName, callingUid);
4252            }
4253            return permissionInfo;
4254        }
4255    }
4256
4257    private int adjustPermissionProtectionFlagsLPr(int protectionLevel,
4258            String packageName, int uid) {
4259        // Signature permission flags area always reported
4260        final int protectionLevelMasked = protectionLevel
4261                & (PermissionInfo.PROTECTION_NORMAL
4262                | PermissionInfo.PROTECTION_DANGEROUS
4263                | PermissionInfo.PROTECTION_SIGNATURE);
4264        if (protectionLevelMasked == PermissionInfo.PROTECTION_SIGNATURE) {
4265            return protectionLevel;
4266        }
4267
4268        // System sees all flags.
4269        final int appId = UserHandle.getAppId(uid);
4270        if (appId == Process.SYSTEM_UID || appId == Process.ROOT_UID
4271                || appId == Process.SHELL_UID) {
4272            return protectionLevel;
4273        }
4274
4275        // Normalize package name to handle renamed packages and static libs
4276        packageName = resolveInternalPackageNameLPr(packageName,
4277                PackageManager.VERSION_CODE_HIGHEST);
4278
4279        // Apps that target O see flags for all protection levels.
4280        final PackageSetting ps = mSettings.mPackages.get(packageName);
4281        if (ps == null) {
4282            return protectionLevel;
4283        }
4284        if (ps.appId != appId) {
4285            return protectionLevel;
4286        }
4287
4288        final PackageParser.Package pkg = mPackages.get(packageName);
4289        if (pkg == null) {
4290            return protectionLevel;
4291        }
4292        if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
4293            return protectionLevelMasked;
4294        }
4295
4296        return protectionLevel;
4297    }
4298
4299    @Override
4300    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4301            int flags) {
4302        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4303            return null;
4304        }
4305        // reader
4306        synchronized (mPackages) {
4307            if (group != null && !mPermissionGroups.containsKey(group)) {
4308                // This is thrown as NameNotFoundException
4309                return null;
4310            }
4311
4312            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4313            for (BasePermission p : mSettings.mPermissions.values()) {
4314                if (group == null) {
4315                    if (p.perm == null || p.perm.info.group == null) {
4316                        out.add(generatePermissionInfo(p, flags));
4317                    }
4318                } else {
4319                    if (p.perm != null && group.equals(p.perm.info.group)) {
4320                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4321                    }
4322                }
4323            }
4324            return new ParceledListSlice<>(out);
4325        }
4326    }
4327
4328    @Override
4329    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4330        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4331            return null;
4332        }
4333        // reader
4334        synchronized (mPackages) {
4335            return PackageParser.generatePermissionGroupInfo(
4336                    mPermissionGroups.get(name), flags);
4337        }
4338    }
4339
4340    @Override
4341    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4342        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4343            return ParceledListSlice.emptyList();
4344        }
4345        // reader
4346        synchronized (mPackages) {
4347            final int N = mPermissionGroups.size();
4348            ArrayList<PermissionGroupInfo> out
4349                    = new ArrayList<PermissionGroupInfo>(N);
4350            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4351                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4352            }
4353            return new ParceledListSlice<>(out);
4354        }
4355    }
4356
4357    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4358            int filterCallingUid, int userId) {
4359        if (!sUserManager.exists(userId)) return null;
4360        PackageSetting ps = mSettings.mPackages.get(packageName);
4361        if (ps != null) {
4362            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4363                return null;
4364            }
4365            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4366                return null;
4367            }
4368            if (ps.pkg == null) {
4369                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4370                if (pInfo != null) {
4371                    return pInfo.applicationInfo;
4372                }
4373                return null;
4374            }
4375            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4376                    ps.readUserState(userId), userId);
4377            if (ai != null) {
4378                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4379            }
4380            return ai;
4381        }
4382        return null;
4383    }
4384
4385    @Override
4386    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4387        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4388    }
4389
4390    /**
4391     * Important: The provided filterCallingUid is used exclusively to filter out applications
4392     * that can be seen based on user state. It's typically the original caller uid prior
4393     * to clearing. Because it can only be provided by trusted code, it's value can be
4394     * trusted and will be used as-is; unlike userId which will be validated by this method.
4395     */
4396    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4397            int filterCallingUid, int userId) {
4398        if (!sUserManager.exists(userId)) return null;
4399        flags = updateFlagsForApplication(flags, userId, packageName);
4400        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4401                false /* requireFullPermission */, false /* checkShell */, "get application info");
4402
4403        // writer
4404        synchronized (mPackages) {
4405            // Normalize package name to handle renamed packages and static libs
4406            packageName = resolveInternalPackageNameLPr(packageName,
4407                    PackageManager.VERSION_CODE_HIGHEST);
4408
4409            PackageParser.Package p = mPackages.get(packageName);
4410            if (DEBUG_PACKAGE_INFO) Log.v(
4411                    TAG, "getApplicationInfo " + packageName
4412                    + ": " + p);
4413            if (p != null) {
4414                PackageSetting ps = mSettings.mPackages.get(packageName);
4415                if (ps == null) return null;
4416                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4417                    return null;
4418                }
4419                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4420                    return null;
4421                }
4422                // Note: isEnabledLP() does not apply here - always return info
4423                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4424                        p, flags, ps.readUserState(userId), userId);
4425                if (ai != null) {
4426                    ai.packageName = resolveExternalPackageNameLPr(p);
4427                }
4428                return ai;
4429            }
4430            if ("android".equals(packageName)||"system".equals(packageName)) {
4431                return mAndroidApplication;
4432            }
4433            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4434                // Already generates the external package name
4435                return generateApplicationInfoFromSettingsLPw(packageName,
4436                        flags, filterCallingUid, userId);
4437            }
4438        }
4439        return null;
4440    }
4441
4442    private String normalizePackageNameLPr(String packageName) {
4443        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4444        return normalizedPackageName != null ? normalizedPackageName : packageName;
4445    }
4446
4447    @Override
4448    public void deletePreloadsFileCache() {
4449        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4450            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4451        }
4452        File dir = Environment.getDataPreloadsFileCacheDirectory();
4453        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4454        FileUtils.deleteContents(dir);
4455    }
4456
4457    @Override
4458    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4459            final int storageFlags, final IPackageDataObserver observer) {
4460        mContext.enforceCallingOrSelfPermission(
4461                android.Manifest.permission.CLEAR_APP_CACHE, null);
4462        mHandler.post(() -> {
4463            boolean success = false;
4464            try {
4465                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4466                success = true;
4467            } catch (IOException e) {
4468                Slog.w(TAG, e);
4469            }
4470            if (observer != null) {
4471                try {
4472                    observer.onRemoveCompleted(null, success);
4473                } catch (RemoteException e) {
4474                    Slog.w(TAG, e);
4475                }
4476            }
4477        });
4478    }
4479
4480    @Override
4481    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4482            final int storageFlags, final IntentSender pi) {
4483        mContext.enforceCallingOrSelfPermission(
4484                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4485        mHandler.post(() -> {
4486            boolean success = false;
4487            try {
4488                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4489                success = true;
4490            } catch (IOException e) {
4491                Slog.w(TAG, e);
4492            }
4493            if (pi != null) {
4494                try {
4495                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4496                } catch (SendIntentException e) {
4497                    Slog.w(TAG, e);
4498                }
4499            }
4500        });
4501    }
4502
4503    /**
4504     * Blocking call to clear various types of cached data across the system
4505     * until the requested bytes are available.
4506     */
4507    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4508        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4509        final File file = storage.findPathForUuid(volumeUuid);
4510        if (file.getUsableSpace() >= bytes) return;
4511
4512        if (ENABLE_FREE_CACHE_V2) {
4513            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4514                    volumeUuid);
4515            final boolean aggressive = (storageFlags
4516                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4517            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4518
4519            // 1. Pre-flight to determine if we have any chance to succeed
4520            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4521            if (internalVolume && (aggressive || SystemProperties
4522                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4523                deletePreloadsFileCache();
4524                if (file.getUsableSpace() >= bytes) return;
4525            }
4526
4527            // 3. Consider parsed APK data (aggressive only)
4528            if (internalVolume && aggressive) {
4529                FileUtils.deleteContents(mCacheDir);
4530                if (file.getUsableSpace() >= bytes) return;
4531            }
4532
4533            // 4. Consider cached app data (above quotas)
4534            try {
4535                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4536                        Installer.FLAG_FREE_CACHE_V2);
4537            } catch (InstallerException ignored) {
4538            }
4539            if (file.getUsableSpace() >= bytes) return;
4540
4541            // 5. Consider shared libraries with refcount=0 and age>min cache period
4542            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4543                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4544                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4545                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4546                return;
4547            }
4548
4549            // 6. Consider dexopt output (aggressive only)
4550            // TODO: Implement
4551
4552            // 7. Consider installed instant apps unused longer than min cache period
4553            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4554                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4555                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4556                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4557                return;
4558            }
4559
4560            // 8. Consider cached app data (below quotas)
4561            try {
4562                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4563                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4564            } catch (InstallerException ignored) {
4565            }
4566            if (file.getUsableSpace() >= bytes) return;
4567
4568            // 9. Consider DropBox entries
4569            // TODO: Implement
4570
4571            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4572            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4573                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4574                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4575                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4576                return;
4577            }
4578        } else {
4579            try {
4580                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4581            } catch (InstallerException ignored) {
4582            }
4583            if (file.getUsableSpace() >= bytes) return;
4584        }
4585
4586        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4587    }
4588
4589    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4590            throws IOException {
4591        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4592        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4593
4594        List<VersionedPackage> packagesToDelete = null;
4595        final long now = System.currentTimeMillis();
4596
4597        synchronized (mPackages) {
4598            final int[] allUsers = sUserManager.getUserIds();
4599            final int libCount = mSharedLibraries.size();
4600            for (int i = 0; i < libCount; i++) {
4601                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4602                if (versionedLib == null) {
4603                    continue;
4604                }
4605                final int versionCount = versionedLib.size();
4606                for (int j = 0; j < versionCount; j++) {
4607                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4608                    // Skip packages that are not static shared libs.
4609                    if (!libInfo.isStatic()) {
4610                        break;
4611                    }
4612                    // Important: We skip static shared libs used for some user since
4613                    // in such a case we need to keep the APK on the device. The check for
4614                    // a lib being used for any user is performed by the uninstall call.
4615                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4616                    // Resolve the package name - we use synthetic package names internally
4617                    final String internalPackageName = resolveInternalPackageNameLPr(
4618                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4619                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4620                    // Skip unused static shared libs cached less than the min period
4621                    // to prevent pruning a lib needed by a subsequently installed package.
4622                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4623                        continue;
4624                    }
4625                    if (packagesToDelete == null) {
4626                        packagesToDelete = new ArrayList<>();
4627                    }
4628                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4629                            declaringPackage.getVersionCode()));
4630                }
4631            }
4632        }
4633
4634        if (packagesToDelete != null) {
4635            final int packageCount = packagesToDelete.size();
4636            for (int i = 0; i < packageCount; i++) {
4637                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4638                // Delete the package synchronously (will fail of the lib used for any user).
4639                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4640                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4641                                == PackageManager.DELETE_SUCCEEDED) {
4642                    if (volume.getUsableSpace() >= neededSpace) {
4643                        return true;
4644                    }
4645                }
4646            }
4647        }
4648
4649        return false;
4650    }
4651
4652    /**
4653     * Update given flags based on encryption status of current user.
4654     */
4655    private int updateFlags(int flags, int userId) {
4656        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4657                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4658            // Caller expressed an explicit opinion about what encryption
4659            // aware/unaware components they want to see, so fall through and
4660            // give them what they want
4661        } else {
4662            // Caller expressed no opinion, so match based on user state
4663            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4664                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4665            } else {
4666                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4667            }
4668        }
4669        return flags;
4670    }
4671
4672    private UserManagerInternal getUserManagerInternal() {
4673        if (mUserManagerInternal == null) {
4674            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4675        }
4676        return mUserManagerInternal;
4677    }
4678
4679    private DeviceIdleController.LocalService getDeviceIdleController() {
4680        if (mDeviceIdleController == null) {
4681            mDeviceIdleController =
4682                    LocalServices.getService(DeviceIdleController.LocalService.class);
4683        }
4684        return mDeviceIdleController;
4685    }
4686
4687    /**
4688     * Update given flags when being used to request {@link PackageInfo}.
4689     */
4690    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4691        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4692        boolean triaged = true;
4693        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4694                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4695            // Caller is asking for component details, so they'd better be
4696            // asking for specific encryption matching behavior, or be triaged
4697            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4698                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4699                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4700                triaged = false;
4701            }
4702        }
4703        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4704                | PackageManager.MATCH_SYSTEM_ONLY
4705                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4706            triaged = false;
4707        }
4708        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4709            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4710                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4711                    + Debug.getCallers(5));
4712        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4713                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4714            // If the caller wants all packages and has a restricted profile associated with it,
4715            // then match all users. This is to make sure that launchers that need to access work
4716            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4717            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4718            flags |= PackageManager.MATCH_ANY_USER;
4719        }
4720        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4721            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4722                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4723        }
4724        return updateFlags(flags, userId);
4725    }
4726
4727    /**
4728     * Update given flags when being used to request {@link ApplicationInfo}.
4729     */
4730    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4731        return updateFlagsForPackage(flags, userId, cookie);
4732    }
4733
4734    /**
4735     * Update given flags when being used to request {@link ComponentInfo}.
4736     */
4737    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4738        if (cookie instanceof Intent) {
4739            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4740                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4741            }
4742        }
4743
4744        boolean triaged = true;
4745        // Caller is asking for component details, so they'd better be
4746        // asking for specific encryption matching behavior, or be triaged
4747        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4748                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4749                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4750            triaged = false;
4751        }
4752        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4753            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4754                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4755        }
4756
4757        return updateFlags(flags, userId);
4758    }
4759
4760    /**
4761     * Update given intent when being used to request {@link ResolveInfo}.
4762     */
4763    private Intent updateIntentForResolve(Intent intent) {
4764        if (intent.getSelector() != null) {
4765            intent = intent.getSelector();
4766        }
4767        if (DEBUG_PREFERRED) {
4768            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4769        }
4770        return intent;
4771    }
4772
4773    /**
4774     * Update given flags when being used to request {@link ResolveInfo}.
4775     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4776     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4777     * flag set. However, this flag is only honoured in three circumstances:
4778     * <ul>
4779     * <li>when called from a system process</li>
4780     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4781     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4782     * action and a {@code android.intent.category.BROWSABLE} category</li>
4783     * </ul>
4784     */
4785    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4786        return updateFlagsForResolve(flags, userId, intent, callingUid,
4787                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4788    }
4789    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4790            boolean wantInstantApps) {
4791        return updateFlagsForResolve(flags, userId, intent, callingUid,
4792                wantInstantApps, false /*onlyExposedExplicitly*/);
4793    }
4794    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4795            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4796        // Safe mode means we shouldn't match any third-party components
4797        if (mSafeMode) {
4798            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4799        }
4800        if (getInstantAppPackageName(callingUid) != null) {
4801            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4802            if (onlyExposedExplicitly) {
4803                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4804            }
4805            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4806            flags |= PackageManager.MATCH_INSTANT;
4807        } else {
4808            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4809            final boolean allowMatchInstant =
4810                    (wantInstantApps
4811                            && Intent.ACTION_VIEW.equals(intent.getAction())
4812                            && hasWebURI(intent))
4813                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4814            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4815                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4816            if (!allowMatchInstant) {
4817                flags &= ~PackageManager.MATCH_INSTANT;
4818            }
4819        }
4820        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4821    }
4822
4823    @Override
4824    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4825        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4826    }
4827
4828    /**
4829     * Important: The provided filterCallingUid is used exclusively to filter out activities
4830     * that can be seen based on user state. It's typically the original caller uid prior
4831     * to clearing. Because it can only be provided by trusted code, it's value can be
4832     * trusted and will be used as-is; unlike userId which will be validated by this method.
4833     */
4834    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4835            int filterCallingUid, int userId) {
4836        if (!sUserManager.exists(userId)) return null;
4837        flags = updateFlagsForComponent(flags, userId, component);
4838        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4839                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4840        synchronized (mPackages) {
4841            PackageParser.Activity a = mActivities.mActivities.get(component);
4842
4843            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4844            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4845                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4846                if (ps == null) return null;
4847                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4848                    return null;
4849                }
4850                return PackageParser.generateActivityInfo(
4851                        a, flags, ps.readUserState(userId), userId);
4852            }
4853            if (mResolveComponentName.equals(component)) {
4854                return PackageParser.generateActivityInfo(
4855                        mResolveActivity, flags, new PackageUserState(), userId);
4856            }
4857        }
4858        return null;
4859    }
4860
4861    @Override
4862    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4863            String resolvedType) {
4864        synchronized (mPackages) {
4865            if (component.equals(mResolveComponentName)) {
4866                // The resolver supports EVERYTHING!
4867                return true;
4868            }
4869            final int callingUid = Binder.getCallingUid();
4870            final int callingUserId = UserHandle.getUserId(callingUid);
4871            PackageParser.Activity a = mActivities.mActivities.get(component);
4872            if (a == null) {
4873                return false;
4874            }
4875            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4876            if (ps == null) {
4877                return false;
4878            }
4879            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4880                return false;
4881            }
4882            for (int i=0; i<a.intents.size(); i++) {
4883                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4884                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4885                    return true;
4886                }
4887            }
4888            return false;
4889        }
4890    }
4891
4892    @Override
4893    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4894        if (!sUserManager.exists(userId)) return null;
4895        final int callingUid = Binder.getCallingUid();
4896        flags = updateFlagsForComponent(flags, userId, component);
4897        enforceCrossUserPermission(callingUid, userId,
4898                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4899        synchronized (mPackages) {
4900            PackageParser.Activity a = mReceivers.mActivities.get(component);
4901            if (DEBUG_PACKAGE_INFO) Log.v(
4902                TAG, "getReceiverInfo " + component + ": " + a);
4903            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4904                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4905                if (ps == null) return null;
4906                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4907                    return null;
4908                }
4909                return PackageParser.generateActivityInfo(
4910                        a, flags, ps.readUserState(userId), userId);
4911            }
4912        }
4913        return null;
4914    }
4915
4916    @Override
4917    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4918            int flags, int userId) {
4919        if (!sUserManager.exists(userId)) return null;
4920        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4921        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4922            return null;
4923        }
4924
4925        flags = updateFlagsForPackage(flags, userId, null);
4926
4927        final boolean canSeeStaticLibraries =
4928                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4929                        == PERMISSION_GRANTED
4930                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4931                        == PERMISSION_GRANTED
4932                || canRequestPackageInstallsInternal(packageName,
4933                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4934                        false  /* throwIfPermNotDeclared*/)
4935                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4936                        == PERMISSION_GRANTED;
4937
4938        synchronized (mPackages) {
4939            List<SharedLibraryInfo> result = null;
4940
4941            final int libCount = mSharedLibraries.size();
4942            for (int i = 0; i < libCount; i++) {
4943                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4944                if (versionedLib == null) {
4945                    continue;
4946                }
4947
4948                final int versionCount = versionedLib.size();
4949                for (int j = 0; j < versionCount; j++) {
4950                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4951                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4952                        break;
4953                    }
4954                    final long identity = Binder.clearCallingIdentity();
4955                    try {
4956                        PackageInfo packageInfo = getPackageInfoVersioned(
4957                                libInfo.getDeclaringPackage(), flags
4958                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4959                        if (packageInfo == null) {
4960                            continue;
4961                        }
4962                    } finally {
4963                        Binder.restoreCallingIdentity(identity);
4964                    }
4965
4966                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4967                            libInfo.getVersion(), libInfo.getType(),
4968                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4969                            flags, userId));
4970
4971                    if (result == null) {
4972                        result = new ArrayList<>();
4973                    }
4974                    result.add(resLibInfo);
4975                }
4976            }
4977
4978            return result != null ? new ParceledListSlice<>(result) : null;
4979        }
4980    }
4981
4982    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4983            SharedLibraryInfo libInfo, int flags, int userId) {
4984        List<VersionedPackage> versionedPackages = null;
4985        final int packageCount = mSettings.mPackages.size();
4986        for (int i = 0; i < packageCount; i++) {
4987            PackageSetting ps = mSettings.mPackages.valueAt(i);
4988
4989            if (ps == null) {
4990                continue;
4991            }
4992
4993            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4994                continue;
4995            }
4996
4997            final String libName = libInfo.getName();
4998            if (libInfo.isStatic()) {
4999                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5000                if (libIdx < 0) {
5001                    continue;
5002                }
5003                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
5004                    continue;
5005                }
5006                if (versionedPackages == null) {
5007                    versionedPackages = new ArrayList<>();
5008                }
5009                // If the dependent is a static shared lib, use the public package name
5010                String dependentPackageName = ps.name;
5011                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5012                    dependentPackageName = ps.pkg.manifestPackageName;
5013                }
5014                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5015            } else if (ps.pkg != null) {
5016                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5017                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5018                    if (versionedPackages == null) {
5019                        versionedPackages = new ArrayList<>();
5020                    }
5021                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5022                }
5023            }
5024        }
5025
5026        return versionedPackages;
5027    }
5028
5029    @Override
5030    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5031        if (!sUserManager.exists(userId)) return null;
5032        final int callingUid = Binder.getCallingUid();
5033        flags = updateFlagsForComponent(flags, userId, component);
5034        enforceCrossUserPermission(callingUid, userId,
5035                false /* requireFullPermission */, false /* checkShell */, "get service info");
5036        synchronized (mPackages) {
5037            PackageParser.Service s = mServices.mServices.get(component);
5038            if (DEBUG_PACKAGE_INFO) Log.v(
5039                TAG, "getServiceInfo " + component + ": " + s);
5040            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5041                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5042                if (ps == null) return null;
5043                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5044                    return null;
5045                }
5046                return PackageParser.generateServiceInfo(
5047                        s, flags, ps.readUserState(userId), userId);
5048            }
5049        }
5050        return null;
5051    }
5052
5053    @Override
5054    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5055        if (!sUserManager.exists(userId)) return null;
5056        final int callingUid = Binder.getCallingUid();
5057        flags = updateFlagsForComponent(flags, userId, component);
5058        enforceCrossUserPermission(callingUid, userId,
5059                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5060        synchronized (mPackages) {
5061            PackageParser.Provider p = mProviders.mProviders.get(component);
5062            if (DEBUG_PACKAGE_INFO) Log.v(
5063                TAG, "getProviderInfo " + component + ": " + p);
5064            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5065                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5066                if (ps == null) return null;
5067                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5068                    return null;
5069                }
5070                return PackageParser.generateProviderInfo(
5071                        p, flags, ps.readUserState(userId), userId);
5072            }
5073        }
5074        return null;
5075    }
5076
5077    @Override
5078    public String[] getSystemSharedLibraryNames() {
5079        // allow instant applications
5080        synchronized (mPackages) {
5081            Set<String> libs = null;
5082            final int libCount = mSharedLibraries.size();
5083            for (int i = 0; i < libCount; i++) {
5084                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5085                if (versionedLib == null) {
5086                    continue;
5087                }
5088                final int versionCount = versionedLib.size();
5089                for (int j = 0; j < versionCount; j++) {
5090                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5091                    if (!libEntry.info.isStatic()) {
5092                        if (libs == null) {
5093                            libs = new ArraySet<>();
5094                        }
5095                        libs.add(libEntry.info.getName());
5096                        break;
5097                    }
5098                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5099                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5100                            UserHandle.getUserId(Binder.getCallingUid()),
5101                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5102                        if (libs == null) {
5103                            libs = new ArraySet<>();
5104                        }
5105                        libs.add(libEntry.info.getName());
5106                        break;
5107                    }
5108                }
5109            }
5110
5111            if (libs != null) {
5112                String[] libsArray = new String[libs.size()];
5113                libs.toArray(libsArray);
5114                return libsArray;
5115            }
5116
5117            return null;
5118        }
5119    }
5120
5121    @Override
5122    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5123        // allow instant applications
5124        synchronized (mPackages) {
5125            return mServicesSystemSharedLibraryPackageName;
5126        }
5127    }
5128
5129    @Override
5130    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5131        // allow instant applications
5132        synchronized (mPackages) {
5133            return mSharedSystemSharedLibraryPackageName;
5134        }
5135    }
5136
5137    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5138        for (int i = userList.length - 1; i >= 0; --i) {
5139            final int userId = userList[i];
5140            // don't add instant app to the list of updates
5141            if (pkgSetting.getInstantApp(userId)) {
5142                continue;
5143            }
5144            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5145            if (changedPackages == null) {
5146                changedPackages = new SparseArray<>();
5147                mChangedPackages.put(userId, changedPackages);
5148            }
5149            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5150            if (sequenceNumbers == null) {
5151                sequenceNumbers = new HashMap<>();
5152                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5153            }
5154            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5155            if (sequenceNumber != null) {
5156                changedPackages.remove(sequenceNumber);
5157            }
5158            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5159            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5160        }
5161        mChangedPackagesSequenceNumber++;
5162    }
5163
5164    @Override
5165    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5166        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5167            return null;
5168        }
5169        synchronized (mPackages) {
5170            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5171                return null;
5172            }
5173            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5174            if (changedPackages == null) {
5175                return null;
5176            }
5177            final List<String> packageNames =
5178                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5179            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5180                final String packageName = changedPackages.get(i);
5181                if (packageName != null) {
5182                    packageNames.add(packageName);
5183                }
5184            }
5185            return packageNames.isEmpty()
5186                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5187        }
5188    }
5189
5190    @Override
5191    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5192        // allow instant applications
5193        ArrayList<FeatureInfo> res;
5194        synchronized (mAvailableFeatures) {
5195            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5196            res.addAll(mAvailableFeatures.values());
5197        }
5198        final FeatureInfo fi = new FeatureInfo();
5199        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5200                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5201        res.add(fi);
5202
5203        return new ParceledListSlice<>(res);
5204    }
5205
5206    @Override
5207    public boolean hasSystemFeature(String name, int version) {
5208        // allow instant applications
5209        synchronized (mAvailableFeatures) {
5210            final FeatureInfo feat = mAvailableFeatures.get(name);
5211            if (feat == null) {
5212                return false;
5213            } else {
5214                return feat.version >= version;
5215            }
5216        }
5217    }
5218
5219    @Override
5220    public int checkPermission(String permName, String pkgName, int userId) {
5221        if (!sUserManager.exists(userId)) {
5222            return PackageManager.PERMISSION_DENIED;
5223        }
5224        final int callingUid = Binder.getCallingUid();
5225
5226        synchronized (mPackages) {
5227            final PackageParser.Package p = mPackages.get(pkgName);
5228            if (p != null && p.mExtras != null) {
5229                final PackageSetting ps = (PackageSetting) p.mExtras;
5230                if (filterAppAccessLPr(ps, callingUid, userId)) {
5231                    return PackageManager.PERMISSION_DENIED;
5232                }
5233                final boolean instantApp = ps.getInstantApp(userId);
5234                final PermissionsState permissionsState = ps.getPermissionsState();
5235                if (permissionsState.hasPermission(permName, userId)) {
5236                    if (instantApp) {
5237                        BasePermission bp = mSettings.mPermissions.get(permName);
5238                        if (bp != null && bp.isInstant()) {
5239                            return PackageManager.PERMISSION_GRANTED;
5240                        }
5241                    } else {
5242                        return PackageManager.PERMISSION_GRANTED;
5243                    }
5244                }
5245                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5246                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5247                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5248                    return PackageManager.PERMISSION_GRANTED;
5249                }
5250            }
5251        }
5252
5253        return PackageManager.PERMISSION_DENIED;
5254    }
5255
5256    @Override
5257    public int checkUidPermission(String permName, int uid) {
5258        final int callingUid = Binder.getCallingUid();
5259        final int callingUserId = UserHandle.getUserId(callingUid);
5260        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5261        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5262        final int userId = UserHandle.getUserId(uid);
5263        if (!sUserManager.exists(userId)) {
5264            return PackageManager.PERMISSION_DENIED;
5265        }
5266
5267        synchronized (mPackages) {
5268            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5269            if (obj != null) {
5270                if (obj instanceof SharedUserSetting) {
5271                    if (isCallerInstantApp) {
5272                        return PackageManager.PERMISSION_DENIED;
5273                    }
5274                } else if (obj instanceof PackageSetting) {
5275                    final PackageSetting ps = (PackageSetting) obj;
5276                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5277                        return PackageManager.PERMISSION_DENIED;
5278                    }
5279                }
5280                final SettingBase settingBase = (SettingBase) obj;
5281                final PermissionsState permissionsState = settingBase.getPermissionsState();
5282                if (permissionsState.hasPermission(permName, userId)) {
5283                    if (isUidInstantApp) {
5284                        BasePermission bp = mSettings.mPermissions.get(permName);
5285                        if (bp != null && bp.isInstant()) {
5286                            return PackageManager.PERMISSION_GRANTED;
5287                        }
5288                    } else {
5289                        return PackageManager.PERMISSION_GRANTED;
5290                    }
5291                }
5292                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5293                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5294                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5295                    return PackageManager.PERMISSION_GRANTED;
5296                }
5297            } else {
5298                ArraySet<String> perms = mSystemPermissions.get(uid);
5299                if (perms != null) {
5300                    if (perms.contains(permName)) {
5301                        return PackageManager.PERMISSION_GRANTED;
5302                    }
5303                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5304                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5305                        return PackageManager.PERMISSION_GRANTED;
5306                    }
5307                }
5308            }
5309        }
5310
5311        return PackageManager.PERMISSION_DENIED;
5312    }
5313
5314    @Override
5315    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5316        if (UserHandle.getCallingUserId() != userId) {
5317            mContext.enforceCallingPermission(
5318                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5319                    "isPermissionRevokedByPolicy for user " + userId);
5320        }
5321
5322        if (checkPermission(permission, packageName, userId)
5323                == PackageManager.PERMISSION_GRANTED) {
5324            return false;
5325        }
5326
5327        final int callingUid = Binder.getCallingUid();
5328        if (getInstantAppPackageName(callingUid) != null) {
5329            if (!isCallerSameApp(packageName, callingUid)) {
5330                return false;
5331            }
5332        } else {
5333            if (isInstantApp(packageName, userId)) {
5334                return false;
5335            }
5336        }
5337
5338        final long identity = Binder.clearCallingIdentity();
5339        try {
5340            final int flags = getPermissionFlags(permission, packageName, userId);
5341            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5342        } finally {
5343            Binder.restoreCallingIdentity(identity);
5344        }
5345    }
5346
5347    @Override
5348    public String getPermissionControllerPackageName() {
5349        synchronized (mPackages) {
5350            return mRequiredInstallerPackage;
5351        }
5352    }
5353
5354    /**
5355     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5356     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5357     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5358     * @param message the message to log on security exception
5359     */
5360    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5361            boolean checkShell, String message) {
5362        if (userId < 0) {
5363            throw new IllegalArgumentException("Invalid userId " + userId);
5364        }
5365        if (checkShell) {
5366            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5367        }
5368        if (userId == UserHandle.getUserId(callingUid)) return;
5369        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5370            if (requireFullPermission) {
5371                mContext.enforceCallingOrSelfPermission(
5372                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5373            } else {
5374                try {
5375                    mContext.enforceCallingOrSelfPermission(
5376                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5377                } catch (SecurityException se) {
5378                    mContext.enforceCallingOrSelfPermission(
5379                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5380                }
5381            }
5382        }
5383    }
5384
5385    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5386        if (callingUid == Process.SHELL_UID) {
5387            if (userHandle >= 0
5388                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5389                throw new SecurityException("Shell does not have permission to access user "
5390                        + userHandle);
5391            } else if (userHandle < 0) {
5392                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5393                        + Debug.getCallers(3));
5394            }
5395        }
5396    }
5397
5398    private BasePermission findPermissionTreeLP(String permName) {
5399        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5400            if (permName.startsWith(bp.name) &&
5401                    permName.length() > bp.name.length() &&
5402                    permName.charAt(bp.name.length()) == '.') {
5403                return bp;
5404            }
5405        }
5406        return null;
5407    }
5408
5409    private BasePermission checkPermissionTreeLP(String permName) {
5410        if (permName != null) {
5411            BasePermission bp = findPermissionTreeLP(permName);
5412            if (bp != null) {
5413                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5414                    return bp;
5415                }
5416                throw new SecurityException("Calling uid "
5417                        + Binder.getCallingUid()
5418                        + " is not allowed to add to permission tree "
5419                        + bp.name + " owned by uid " + bp.uid);
5420            }
5421        }
5422        throw new SecurityException("No permission tree found for " + permName);
5423    }
5424
5425    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5426        if (s1 == null) {
5427            return s2 == null;
5428        }
5429        if (s2 == null) {
5430            return false;
5431        }
5432        if (s1.getClass() != s2.getClass()) {
5433            return false;
5434        }
5435        return s1.equals(s2);
5436    }
5437
5438    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5439        if (pi1.icon != pi2.icon) return false;
5440        if (pi1.logo != pi2.logo) return false;
5441        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5442        if (!compareStrings(pi1.name, pi2.name)) return false;
5443        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5444        // We'll take care of setting this one.
5445        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5446        // These are not currently stored in settings.
5447        //if (!compareStrings(pi1.group, pi2.group)) return false;
5448        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5449        //if (pi1.labelRes != pi2.labelRes) return false;
5450        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5451        return true;
5452    }
5453
5454    int permissionInfoFootprint(PermissionInfo info) {
5455        int size = info.name.length();
5456        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5457        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5458        return size;
5459    }
5460
5461    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5462        int size = 0;
5463        for (BasePermission perm : mSettings.mPermissions.values()) {
5464            if (perm.uid == tree.uid) {
5465                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5466            }
5467        }
5468        return size;
5469    }
5470
5471    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5472        // We calculate the max size of permissions defined by this uid and throw
5473        // if that plus the size of 'info' would exceed our stated maximum.
5474        if (tree.uid != Process.SYSTEM_UID) {
5475            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5476            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5477                throw new SecurityException("Permission tree size cap exceeded");
5478            }
5479        }
5480    }
5481
5482    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5483        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5484            throw new SecurityException("Instant apps can't add permissions");
5485        }
5486        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5487            throw new SecurityException("Label must be specified in permission");
5488        }
5489        BasePermission tree = checkPermissionTreeLP(info.name);
5490        BasePermission bp = mSettings.mPermissions.get(info.name);
5491        boolean added = bp == null;
5492        boolean changed = true;
5493        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5494        if (added) {
5495            enforcePermissionCapLocked(info, tree);
5496            bp = new BasePermission(info.name, tree.sourcePackage,
5497                    BasePermission.TYPE_DYNAMIC);
5498        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5499            throw new SecurityException(
5500                    "Not allowed to modify non-dynamic permission "
5501                    + info.name);
5502        } else {
5503            if (bp.protectionLevel == fixedLevel
5504                    && bp.perm.owner.equals(tree.perm.owner)
5505                    && bp.uid == tree.uid
5506                    && comparePermissionInfos(bp.perm.info, info)) {
5507                changed = false;
5508            }
5509        }
5510        bp.protectionLevel = fixedLevel;
5511        info = new PermissionInfo(info);
5512        info.protectionLevel = fixedLevel;
5513        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5514        bp.perm.info.packageName = tree.perm.info.packageName;
5515        bp.uid = tree.uid;
5516        if (added) {
5517            mSettings.mPermissions.put(info.name, bp);
5518        }
5519        if (changed) {
5520            if (!async) {
5521                mSettings.writeLPr();
5522            } else {
5523                scheduleWriteSettingsLocked();
5524            }
5525        }
5526        return added;
5527    }
5528
5529    @Override
5530    public boolean addPermission(PermissionInfo info) {
5531        synchronized (mPackages) {
5532            return addPermissionLocked(info, false);
5533        }
5534    }
5535
5536    @Override
5537    public boolean addPermissionAsync(PermissionInfo info) {
5538        synchronized (mPackages) {
5539            return addPermissionLocked(info, true);
5540        }
5541    }
5542
5543    @Override
5544    public void removePermission(String name) {
5545        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5546            throw new SecurityException("Instant applications don't have access to this method");
5547        }
5548        synchronized (mPackages) {
5549            checkPermissionTreeLP(name);
5550            BasePermission bp = mSettings.mPermissions.get(name);
5551            if (bp != null) {
5552                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5553                    throw new SecurityException(
5554                            "Not allowed to modify non-dynamic permission "
5555                            + name);
5556                }
5557                mSettings.mPermissions.remove(name);
5558                mSettings.writeLPr();
5559            }
5560        }
5561    }
5562
5563    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5564            PackageParser.Package pkg, BasePermission bp) {
5565        int index = pkg.requestedPermissions.indexOf(bp.name);
5566        if (index == -1) {
5567            throw new SecurityException("Package " + pkg.packageName
5568                    + " has not requested permission " + bp.name);
5569        }
5570        if (!bp.isRuntime() && !bp.isDevelopment()) {
5571            throw new SecurityException("Permission " + bp.name
5572                    + " is not a changeable permission type");
5573        }
5574    }
5575
5576    @Override
5577    public void grantRuntimePermission(String packageName, String name, final int userId) {
5578        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5579    }
5580
5581    private void grantRuntimePermission(String packageName, String name, final int userId,
5582            boolean overridePolicy) {
5583        if (!sUserManager.exists(userId)) {
5584            Log.e(TAG, "No such user:" + userId);
5585            return;
5586        }
5587        final int callingUid = Binder.getCallingUid();
5588
5589        mContext.enforceCallingOrSelfPermission(
5590                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5591                "grantRuntimePermission");
5592
5593        enforceCrossUserPermission(callingUid, userId,
5594                true /* requireFullPermission */, true /* checkShell */,
5595                "grantRuntimePermission");
5596
5597        final int uid;
5598        final PackageSetting ps;
5599
5600        synchronized (mPackages) {
5601            final PackageParser.Package pkg = mPackages.get(packageName);
5602            if (pkg == null) {
5603                throw new IllegalArgumentException("Unknown package: " + packageName);
5604            }
5605            final BasePermission bp = mSettings.mPermissions.get(name);
5606            if (bp == null) {
5607                throw new IllegalArgumentException("Unknown permission: " + name);
5608            }
5609            ps = (PackageSetting) pkg.mExtras;
5610            if (ps == null
5611                    || filterAppAccessLPr(ps, callingUid, userId)) {
5612                throw new IllegalArgumentException("Unknown package: " + packageName);
5613            }
5614
5615            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5616
5617            // If a permission review is required for legacy apps we represent
5618            // their permissions as always granted runtime ones since we need
5619            // to keep the review required permission flag per user while an
5620            // install permission's state is shared across all users.
5621            if (mPermissionReviewRequired
5622                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5623                    && bp.isRuntime()) {
5624                return;
5625            }
5626
5627            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5628
5629            final PermissionsState permissionsState = ps.getPermissionsState();
5630
5631            final int flags = permissionsState.getPermissionFlags(name, userId);
5632            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5633                throw new SecurityException("Cannot grant system fixed permission "
5634                        + name + " for package " + packageName);
5635            }
5636            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5637                throw new SecurityException("Cannot grant policy fixed permission "
5638                        + name + " for package " + packageName);
5639            }
5640
5641            if (bp.isDevelopment()) {
5642                // Development permissions must be handled specially, since they are not
5643                // normal runtime permissions.  For now they apply to all users.
5644                if (permissionsState.grantInstallPermission(bp) !=
5645                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5646                    scheduleWriteSettingsLocked();
5647                }
5648                return;
5649            }
5650
5651            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5652                throw new SecurityException("Cannot grant non-ephemeral permission"
5653                        + name + " for package " + packageName);
5654            }
5655
5656            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5657                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5658                return;
5659            }
5660
5661            final int result = permissionsState.grantRuntimePermission(bp, userId);
5662            switch (result) {
5663                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5664                    return;
5665                }
5666
5667                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5668                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5669                    mHandler.post(new Runnable() {
5670                        @Override
5671                        public void run() {
5672                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5673                        }
5674                    });
5675                }
5676                break;
5677            }
5678
5679            if (bp.isRuntime()) {
5680                logPermissionGranted(mContext, name, packageName);
5681            }
5682
5683            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5684
5685            // Not critical if that is lost - app has to request again.
5686            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5687        }
5688
5689        // Only need to do this if user is initialized. Otherwise it's a new user
5690        // and there are no processes running as the user yet and there's no need
5691        // to make an expensive call to remount processes for the changed permissions.
5692        if (READ_EXTERNAL_STORAGE.equals(name)
5693                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5694            final long token = Binder.clearCallingIdentity();
5695            try {
5696                if (sUserManager.isInitialized(userId)) {
5697                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5698                            StorageManagerInternal.class);
5699                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5700                }
5701            } finally {
5702                Binder.restoreCallingIdentity(token);
5703            }
5704        }
5705    }
5706
5707    @Override
5708    public void revokeRuntimePermission(String packageName, String name, int userId) {
5709        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5710    }
5711
5712    private void revokeRuntimePermission(String packageName, String name, int userId,
5713            boolean overridePolicy) {
5714        if (!sUserManager.exists(userId)) {
5715            Log.e(TAG, "No such user:" + userId);
5716            return;
5717        }
5718
5719        mContext.enforceCallingOrSelfPermission(
5720                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5721                "revokeRuntimePermission");
5722
5723        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5724                true /* requireFullPermission */, true /* checkShell */,
5725                "revokeRuntimePermission");
5726
5727        final int appId;
5728
5729        synchronized (mPackages) {
5730            final PackageParser.Package pkg = mPackages.get(packageName);
5731            if (pkg == null) {
5732                throw new IllegalArgumentException("Unknown package: " + packageName);
5733            }
5734            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5735            if (ps == null
5736                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5737                throw new IllegalArgumentException("Unknown package: " + packageName);
5738            }
5739            final BasePermission bp = mSettings.mPermissions.get(name);
5740            if (bp == null) {
5741                throw new IllegalArgumentException("Unknown permission: " + name);
5742            }
5743
5744            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5745
5746            // If a permission review is required for legacy apps we represent
5747            // their permissions as always granted runtime ones since we need
5748            // to keep the review required permission flag per user while an
5749            // install permission's state is shared across all users.
5750            if (mPermissionReviewRequired
5751                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5752                    && bp.isRuntime()) {
5753                return;
5754            }
5755
5756            final PermissionsState permissionsState = ps.getPermissionsState();
5757
5758            final int flags = permissionsState.getPermissionFlags(name, userId);
5759            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5760                throw new SecurityException("Cannot revoke system fixed permission "
5761                        + name + " for package " + packageName);
5762            }
5763            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5764                throw new SecurityException("Cannot revoke policy fixed permission "
5765                        + name + " for package " + packageName);
5766            }
5767
5768            if (bp.isDevelopment()) {
5769                // Development permissions must be handled specially, since they are not
5770                // normal runtime permissions.  For now they apply to all users.
5771                if (permissionsState.revokeInstallPermission(bp) !=
5772                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5773                    scheduleWriteSettingsLocked();
5774                }
5775                return;
5776            }
5777
5778            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5779                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5780                return;
5781            }
5782
5783            if (bp.isRuntime()) {
5784                logPermissionRevoked(mContext, name, packageName);
5785            }
5786
5787            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5788
5789            // Critical, after this call app should never have the permission.
5790            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5791
5792            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5793        }
5794
5795        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5796    }
5797
5798    /**
5799     * Get the first event id for the permission.
5800     *
5801     * <p>There are four events for each permission: <ul>
5802     *     <li>Request permission: first id + 0</li>
5803     *     <li>Grant permission: first id + 1</li>
5804     *     <li>Request for permission denied: first id + 2</li>
5805     *     <li>Revoke permission: first id + 3</li>
5806     * </ul></p>
5807     *
5808     * @param name name of the permission
5809     *
5810     * @return The first event id for the permission
5811     */
5812    private static int getBaseEventId(@NonNull String name) {
5813        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5814
5815        if (eventIdIndex == -1) {
5816            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5817                    || Build.IS_USER) {
5818                Log.i(TAG, "Unknown permission " + name);
5819
5820                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5821            } else {
5822                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5823                //
5824                // Also update
5825                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5826                // - metrics_constants.proto
5827                throw new IllegalStateException("Unknown permission " + name);
5828            }
5829        }
5830
5831        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5832    }
5833
5834    /**
5835     * Log that a permission was revoked.
5836     *
5837     * @param context Context of the caller
5838     * @param name name of the permission
5839     * @param packageName package permission if for
5840     */
5841    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5842            @NonNull String packageName) {
5843        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5844    }
5845
5846    /**
5847     * Log that a permission request was granted.
5848     *
5849     * @param context Context of the caller
5850     * @param name name of the permission
5851     * @param packageName package permission if for
5852     */
5853    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5854            @NonNull String packageName) {
5855        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5856    }
5857
5858    @Override
5859    public void resetRuntimePermissions() {
5860        mContext.enforceCallingOrSelfPermission(
5861                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5862                "revokeRuntimePermission");
5863
5864        int callingUid = Binder.getCallingUid();
5865        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5866            mContext.enforceCallingOrSelfPermission(
5867                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5868                    "resetRuntimePermissions");
5869        }
5870
5871        synchronized (mPackages) {
5872            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5873            for (int userId : UserManagerService.getInstance().getUserIds()) {
5874                final int packageCount = mPackages.size();
5875                for (int i = 0; i < packageCount; i++) {
5876                    PackageParser.Package pkg = mPackages.valueAt(i);
5877                    if (!(pkg.mExtras instanceof PackageSetting)) {
5878                        continue;
5879                    }
5880                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5881                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5882                }
5883            }
5884        }
5885    }
5886
5887    @Override
5888    public int getPermissionFlags(String name, String packageName, int userId) {
5889        if (!sUserManager.exists(userId)) {
5890            return 0;
5891        }
5892
5893        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5894
5895        final int callingUid = Binder.getCallingUid();
5896        enforceCrossUserPermission(callingUid, userId,
5897                true /* requireFullPermission */, false /* checkShell */,
5898                "getPermissionFlags");
5899
5900        synchronized (mPackages) {
5901            final PackageParser.Package pkg = mPackages.get(packageName);
5902            if (pkg == null) {
5903                return 0;
5904            }
5905            final BasePermission bp = mSettings.mPermissions.get(name);
5906            if (bp == null) {
5907                return 0;
5908            }
5909            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5910            if (ps == null
5911                    || filterAppAccessLPr(ps, callingUid, userId)) {
5912                return 0;
5913            }
5914            PermissionsState permissionsState = ps.getPermissionsState();
5915            return permissionsState.getPermissionFlags(name, userId);
5916        }
5917    }
5918
5919    @Override
5920    public void updatePermissionFlags(String name, String packageName, int flagMask,
5921            int flagValues, int userId) {
5922        if (!sUserManager.exists(userId)) {
5923            return;
5924        }
5925
5926        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5927
5928        final int callingUid = Binder.getCallingUid();
5929        enforceCrossUserPermission(callingUid, userId,
5930                true /* requireFullPermission */, true /* checkShell */,
5931                "updatePermissionFlags");
5932
5933        // Only the system can change these flags and nothing else.
5934        if (getCallingUid() != Process.SYSTEM_UID) {
5935            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5936            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5937            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5938            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5939            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5940        }
5941
5942        synchronized (mPackages) {
5943            final PackageParser.Package pkg = mPackages.get(packageName);
5944            if (pkg == null) {
5945                throw new IllegalArgumentException("Unknown package: " + packageName);
5946            }
5947            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5948            if (ps == null
5949                    || filterAppAccessLPr(ps, callingUid, userId)) {
5950                throw new IllegalArgumentException("Unknown package: " + packageName);
5951            }
5952
5953            final BasePermission bp = mSettings.mPermissions.get(name);
5954            if (bp == null) {
5955                throw new IllegalArgumentException("Unknown permission: " + name);
5956            }
5957
5958            PermissionsState permissionsState = ps.getPermissionsState();
5959
5960            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5961
5962            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5963                // Install and runtime permissions are stored in different places,
5964                // so figure out what permission changed and persist the change.
5965                if (permissionsState.getInstallPermissionState(name) != null) {
5966                    scheduleWriteSettingsLocked();
5967                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5968                        || hadState) {
5969                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5970                }
5971            }
5972        }
5973    }
5974
5975    /**
5976     * Update the permission flags for all packages and runtime permissions of a user in order
5977     * to allow device or profile owner to remove POLICY_FIXED.
5978     */
5979    @Override
5980    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5981        if (!sUserManager.exists(userId)) {
5982            return;
5983        }
5984
5985        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5986
5987        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5988                true /* requireFullPermission */, true /* checkShell */,
5989                "updatePermissionFlagsForAllApps");
5990
5991        // Only the system can change system fixed flags.
5992        if (getCallingUid() != Process.SYSTEM_UID) {
5993            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5994            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5995        }
5996
5997        synchronized (mPackages) {
5998            boolean changed = false;
5999            final int packageCount = mPackages.size();
6000            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
6001                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
6002                final PackageSetting ps = (PackageSetting) pkg.mExtras;
6003                if (ps == null) {
6004                    continue;
6005                }
6006                PermissionsState permissionsState = ps.getPermissionsState();
6007                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
6008                        userId, flagMask, flagValues);
6009            }
6010            if (changed) {
6011                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
6012            }
6013        }
6014    }
6015
6016    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
6017        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
6018                != PackageManager.PERMISSION_GRANTED
6019            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
6020                != PackageManager.PERMISSION_GRANTED) {
6021            throw new SecurityException(message + " requires "
6022                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
6023                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
6024        }
6025    }
6026
6027    @Override
6028    public boolean shouldShowRequestPermissionRationale(String permissionName,
6029            String packageName, int userId) {
6030        if (UserHandle.getCallingUserId() != userId) {
6031            mContext.enforceCallingPermission(
6032                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
6033                    "canShowRequestPermissionRationale for user " + userId);
6034        }
6035
6036        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
6037        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
6038            return false;
6039        }
6040
6041        if (checkPermission(permissionName, packageName, userId)
6042                == PackageManager.PERMISSION_GRANTED) {
6043            return false;
6044        }
6045
6046        final int flags;
6047
6048        final long identity = Binder.clearCallingIdentity();
6049        try {
6050            flags = getPermissionFlags(permissionName,
6051                    packageName, userId);
6052        } finally {
6053            Binder.restoreCallingIdentity(identity);
6054        }
6055
6056        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
6057                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
6058                | PackageManager.FLAG_PERMISSION_USER_FIXED;
6059
6060        if ((flags & fixedFlags) != 0) {
6061            return false;
6062        }
6063
6064        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
6065    }
6066
6067    @Override
6068    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6069        mContext.enforceCallingOrSelfPermission(
6070                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
6071                "addOnPermissionsChangeListener");
6072
6073        synchronized (mPackages) {
6074            mOnPermissionChangeListeners.addListenerLocked(listener);
6075        }
6076    }
6077
6078    @Override
6079    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6080        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6081            throw new SecurityException("Instant applications don't have access to this method");
6082        }
6083        synchronized (mPackages) {
6084            mOnPermissionChangeListeners.removeListenerLocked(listener);
6085        }
6086    }
6087
6088    @Override
6089    public boolean isProtectedBroadcast(String actionName) {
6090        // allow instant applications
6091        synchronized (mProtectedBroadcasts) {
6092            if (mProtectedBroadcasts.contains(actionName)) {
6093                return true;
6094            } else if (actionName != null) {
6095                // TODO: remove these terrible hacks
6096                if (actionName.startsWith("android.net.netmon.lingerExpired")
6097                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
6098                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
6099                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
6100                    return true;
6101                }
6102            }
6103        }
6104        return false;
6105    }
6106
6107    @Override
6108    public int checkSignatures(String pkg1, String pkg2) {
6109        synchronized (mPackages) {
6110            final PackageParser.Package p1 = mPackages.get(pkg1);
6111            final PackageParser.Package p2 = mPackages.get(pkg2);
6112            if (p1 == null || p1.mExtras == null
6113                    || p2 == null || p2.mExtras == null) {
6114                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6115            }
6116            final int callingUid = Binder.getCallingUid();
6117            final int callingUserId = UserHandle.getUserId(callingUid);
6118            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
6119            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
6120            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
6121                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
6122                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6123            }
6124            return compareSignatures(p1.mSignatures, p2.mSignatures);
6125        }
6126    }
6127
6128    @Override
6129    public int checkUidSignatures(int uid1, int uid2) {
6130        final int callingUid = Binder.getCallingUid();
6131        final int callingUserId = UserHandle.getUserId(callingUid);
6132        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6133        // Map to base uids.
6134        uid1 = UserHandle.getAppId(uid1);
6135        uid2 = UserHandle.getAppId(uid2);
6136        // reader
6137        synchronized (mPackages) {
6138            Signature[] s1;
6139            Signature[] s2;
6140            Object obj = mSettings.getUserIdLPr(uid1);
6141            if (obj != null) {
6142                if (obj instanceof SharedUserSetting) {
6143                    if (isCallerInstantApp) {
6144                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6145                    }
6146                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
6147                } else if (obj instanceof PackageSetting) {
6148                    final PackageSetting ps = (PackageSetting) obj;
6149                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6150                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6151                    }
6152                    s1 = ps.signatures.mSignatures;
6153                } else {
6154                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6155                }
6156            } else {
6157                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6158            }
6159            obj = mSettings.getUserIdLPr(uid2);
6160            if (obj != null) {
6161                if (obj instanceof SharedUserSetting) {
6162                    if (isCallerInstantApp) {
6163                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6164                    }
6165                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
6166                } else if (obj instanceof PackageSetting) {
6167                    final PackageSetting ps = (PackageSetting) obj;
6168                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6169                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6170                    }
6171                    s2 = ps.signatures.mSignatures;
6172                } else {
6173                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6174                }
6175            } else {
6176                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6177            }
6178            return compareSignatures(s1, s2);
6179        }
6180    }
6181
6182    /**
6183     * This method should typically only be used when granting or revoking
6184     * permissions, since the app may immediately restart after this call.
6185     * <p>
6186     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
6187     * guard your work against the app being relaunched.
6188     */
6189    private void killUid(int appId, int userId, String reason) {
6190        final long identity = Binder.clearCallingIdentity();
6191        try {
6192            IActivityManager am = ActivityManager.getService();
6193            if (am != null) {
6194                try {
6195                    am.killUid(appId, userId, reason);
6196                } catch (RemoteException e) {
6197                    /* ignore - same process */
6198                }
6199            }
6200        } finally {
6201            Binder.restoreCallingIdentity(identity);
6202        }
6203    }
6204
6205    /**
6206     * Compares two sets of signatures. Returns:
6207     * <br />
6208     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
6209     * <br />
6210     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
6211     * <br />
6212     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
6213     * <br />
6214     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
6215     * <br />
6216     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
6217     */
6218    static int compareSignatures(Signature[] s1, Signature[] s2) {
6219        if (s1 == null) {
6220            return s2 == null
6221                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
6222                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
6223        }
6224
6225        if (s2 == null) {
6226            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
6227        }
6228
6229        if (s1.length != s2.length) {
6230            return PackageManager.SIGNATURE_NO_MATCH;
6231        }
6232
6233        // Since both signature sets are of size 1, we can compare without HashSets.
6234        if (s1.length == 1) {
6235            return s1[0].equals(s2[0]) ?
6236                    PackageManager.SIGNATURE_MATCH :
6237                    PackageManager.SIGNATURE_NO_MATCH;
6238        }
6239
6240        ArraySet<Signature> set1 = new ArraySet<Signature>();
6241        for (Signature sig : s1) {
6242            set1.add(sig);
6243        }
6244        ArraySet<Signature> set2 = new ArraySet<Signature>();
6245        for (Signature sig : s2) {
6246            set2.add(sig);
6247        }
6248        // Make sure s2 contains all signatures in s1.
6249        if (set1.equals(set2)) {
6250            return PackageManager.SIGNATURE_MATCH;
6251        }
6252        return PackageManager.SIGNATURE_NO_MATCH;
6253    }
6254
6255    /**
6256     * If the database version for this type of package (internal storage or
6257     * external storage) is less than the version where package signatures
6258     * were updated, return true.
6259     */
6260    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6261        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6262        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6263    }
6264
6265    /**
6266     * Used for backward compatibility to make sure any packages with
6267     * certificate chains get upgraded to the new style. {@code existingSigs}
6268     * will be in the old format (since they were stored on disk from before the
6269     * system upgrade) and {@code scannedSigs} will be in the newer format.
6270     */
6271    private int compareSignaturesCompat(PackageSignatures existingSigs,
6272            PackageParser.Package scannedPkg) {
6273        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6274            return PackageManager.SIGNATURE_NO_MATCH;
6275        }
6276
6277        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6278        for (Signature sig : existingSigs.mSignatures) {
6279            existingSet.add(sig);
6280        }
6281        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6282        for (Signature sig : scannedPkg.mSignatures) {
6283            try {
6284                Signature[] chainSignatures = sig.getChainSignatures();
6285                for (Signature chainSig : chainSignatures) {
6286                    scannedCompatSet.add(chainSig);
6287                }
6288            } catch (CertificateEncodingException e) {
6289                scannedCompatSet.add(sig);
6290            }
6291        }
6292        /*
6293         * Make sure the expanded scanned set contains all signatures in the
6294         * existing one.
6295         */
6296        if (scannedCompatSet.equals(existingSet)) {
6297            // Migrate the old signatures to the new scheme.
6298            existingSigs.assignSignatures(scannedPkg.mSignatures);
6299            // The new KeySets will be re-added later in the scanning process.
6300            synchronized (mPackages) {
6301                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6302            }
6303            return PackageManager.SIGNATURE_MATCH;
6304        }
6305        return PackageManager.SIGNATURE_NO_MATCH;
6306    }
6307
6308    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6309        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6310        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6311    }
6312
6313    private int compareSignaturesRecover(PackageSignatures existingSigs,
6314            PackageParser.Package scannedPkg) {
6315        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6316            return PackageManager.SIGNATURE_NO_MATCH;
6317        }
6318
6319        String msg = null;
6320        try {
6321            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6322                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6323                        + scannedPkg.packageName);
6324                return PackageManager.SIGNATURE_MATCH;
6325            }
6326        } catch (CertificateException e) {
6327            msg = e.getMessage();
6328        }
6329
6330        logCriticalInfo(Log.INFO,
6331                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6332        return PackageManager.SIGNATURE_NO_MATCH;
6333    }
6334
6335    @Override
6336    public List<String> getAllPackages() {
6337        final int callingUid = Binder.getCallingUid();
6338        final int callingUserId = UserHandle.getUserId(callingUid);
6339        synchronized (mPackages) {
6340            if (canViewInstantApps(callingUid, callingUserId)) {
6341                return new ArrayList<String>(mPackages.keySet());
6342            }
6343            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6344            final List<String> result = new ArrayList<>();
6345            if (instantAppPkgName != null) {
6346                // caller is an instant application; filter unexposed applications
6347                for (PackageParser.Package pkg : mPackages.values()) {
6348                    if (!pkg.visibleToInstantApps) {
6349                        continue;
6350                    }
6351                    result.add(pkg.packageName);
6352                }
6353            } else {
6354                // caller is a normal application; filter instant applications
6355                for (PackageParser.Package pkg : mPackages.values()) {
6356                    final PackageSetting ps =
6357                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6358                    if (ps != null
6359                            && ps.getInstantApp(callingUserId)
6360                            && !mInstantAppRegistry.isInstantAccessGranted(
6361                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6362                        continue;
6363                    }
6364                    result.add(pkg.packageName);
6365                }
6366            }
6367            return result;
6368        }
6369    }
6370
6371    @Override
6372    public String[] getPackagesForUid(int uid) {
6373        final int callingUid = Binder.getCallingUid();
6374        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6375        final int userId = UserHandle.getUserId(uid);
6376        uid = UserHandle.getAppId(uid);
6377        // reader
6378        synchronized (mPackages) {
6379            Object obj = mSettings.getUserIdLPr(uid);
6380            if (obj instanceof SharedUserSetting) {
6381                if (isCallerInstantApp) {
6382                    return null;
6383                }
6384                final SharedUserSetting sus = (SharedUserSetting) obj;
6385                final int N = sus.packages.size();
6386                String[] res = new String[N];
6387                final Iterator<PackageSetting> it = sus.packages.iterator();
6388                int i = 0;
6389                while (it.hasNext()) {
6390                    PackageSetting ps = it.next();
6391                    if (ps.getInstalled(userId)) {
6392                        res[i++] = ps.name;
6393                    } else {
6394                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6395                    }
6396                }
6397                return res;
6398            } else if (obj instanceof PackageSetting) {
6399                final PackageSetting ps = (PackageSetting) obj;
6400                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6401                    return new String[]{ps.name};
6402                }
6403            }
6404        }
6405        return null;
6406    }
6407
6408    @Override
6409    public String getNameForUid(int uid) {
6410        final int callingUid = Binder.getCallingUid();
6411        if (getInstantAppPackageName(callingUid) != null) {
6412            return null;
6413        }
6414        synchronized (mPackages) {
6415            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6416            if (obj instanceof SharedUserSetting) {
6417                final SharedUserSetting sus = (SharedUserSetting) obj;
6418                return sus.name + ":" + sus.userId;
6419            } else if (obj instanceof PackageSetting) {
6420                final PackageSetting ps = (PackageSetting) obj;
6421                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6422                    return null;
6423                }
6424                return ps.name;
6425            }
6426            return null;
6427        }
6428    }
6429
6430    @Override
6431    public String[] getNamesForUids(int[] uids) {
6432        if (uids == null || uids.length == 0) {
6433            return null;
6434        }
6435        final int callingUid = Binder.getCallingUid();
6436        if (getInstantAppPackageName(callingUid) != null) {
6437            return null;
6438        }
6439        final String[] names = new String[uids.length];
6440        synchronized (mPackages) {
6441            for (int i = uids.length - 1; i >= 0; i--) {
6442                final int uid = uids[i];
6443                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6444                if (obj instanceof SharedUserSetting) {
6445                    final SharedUserSetting sus = (SharedUserSetting) obj;
6446                    names[i] = "shared:" + sus.name;
6447                } else if (obj instanceof PackageSetting) {
6448                    final PackageSetting ps = (PackageSetting) obj;
6449                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6450                        names[i] = null;
6451                    } else {
6452                        names[i] = ps.name;
6453                    }
6454                } else {
6455                    names[i] = null;
6456                }
6457            }
6458        }
6459        return names;
6460    }
6461
6462    @Override
6463    public int getUidForSharedUser(String sharedUserName) {
6464        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6465            return -1;
6466        }
6467        if (sharedUserName == null) {
6468            return -1;
6469        }
6470        // reader
6471        synchronized (mPackages) {
6472            SharedUserSetting suid;
6473            try {
6474                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6475                if (suid != null) {
6476                    return suid.userId;
6477                }
6478            } catch (PackageManagerException ignore) {
6479                // can't happen, but, still need to catch it
6480            }
6481            return -1;
6482        }
6483    }
6484
6485    @Override
6486    public int getFlagsForUid(int uid) {
6487        final int callingUid = Binder.getCallingUid();
6488        if (getInstantAppPackageName(callingUid) != null) {
6489            return 0;
6490        }
6491        synchronized (mPackages) {
6492            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6493            if (obj instanceof SharedUserSetting) {
6494                final SharedUserSetting sus = (SharedUserSetting) obj;
6495                return sus.pkgFlags;
6496            } else if (obj instanceof PackageSetting) {
6497                final PackageSetting ps = (PackageSetting) obj;
6498                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6499                    return 0;
6500                }
6501                return ps.pkgFlags;
6502            }
6503        }
6504        return 0;
6505    }
6506
6507    @Override
6508    public int getPrivateFlagsForUid(int uid) {
6509        final int callingUid = Binder.getCallingUid();
6510        if (getInstantAppPackageName(callingUid) != null) {
6511            return 0;
6512        }
6513        synchronized (mPackages) {
6514            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6515            if (obj instanceof SharedUserSetting) {
6516                final SharedUserSetting sus = (SharedUserSetting) obj;
6517                return sus.pkgPrivateFlags;
6518            } else if (obj instanceof PackageSetting) {
6519                final PackageSetting ps = (PackageSetting) obj;
6520                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6521                    return 0;
6522                }
6523                return ps.pkgPrivateFlags;
6524            }
6525        }
6526        return 0;
6527    }
6528
6529    @Override
6530    public boolean isUidPrivileged(int uid) {
6531        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6532            return false;
6533        }
6534        uid = UserHandle.getAppId(uid);
6535        // reader
6536        synchronized (mPackages) {
6537            Object obj = mSettings.getUserIdLPr(uid);
6538            if (obj instanceof SharedUserSetting) {
6539                final SharedUserSetting sus = (SharedUserSetting) obj;
6540                final Iterator<PackageSetting> it = sus.packages.iterator();
6541                while (it.hasNext()) {
6542                    if (it.next().isPrivileged()) {
6543                        return true;
6544                    }
6545                }
6546            } else if (obj instanceof PackageSetting) {
6547                final PackageSetting ps = (PackageSetting) obj;
6548                return ps.isPrivileged();
6549            }
6550        }
6551        return false;
6552    }
6553
6554    @Override
6555    public String[] getAppOpPermissionPackages(String permissionName) {
6556        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6557            return null;
6558        }
6559        synchronized (mPackages) {
6560            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6561            if (pkgs == null) {
6562                return null;
6563            }
6564            return pkgs.toArray(new String[pkgs.size()]);
6565        }
6566    }
6567
6568    @Override
6569    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6570            int flags, int userId) {
6571        return resolveIntentInternal(
6572                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6573    }
6574
6575    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6576            int flags, int userId, boolean resolveForStart) {
6577        try {
6578            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6579
6580            if (!sUserManager.exists(userId)) return null;
6581            final int callingUid = Binder.getCallingUid();
6582            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6583            enforceCrossUserPermission(callingUid, userId,
6584                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6585
6586            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6587            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6588                    flags, callingUid, userId, resolveForStart);
6589            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6590
6591            final ResolveInfo bestChoice =
6592                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6593            return bestChoice;
6594        } finally {
6595            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6596        }
6597    }
6598
6599    @Override
6600    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6601        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6602            throw new SecurityException(
6603                    "findPersistentPreferredActivity can only be run by the system");
6604        }
6605        if (!sUserManager.exists(userId)) {
6606            return null;
6607        }
6608        final int callingUid = Binder.getCallingUid();
6609        intent = updateIntentForResolve(intent);
6610        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6611        final int flags = updateFlagsForResolve(
6612                0, userId, intent, callingUid, false /*includeInstantApps*/);
6613        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6614                userId);
6615        synchronized (mPackages) {
6616            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6617                    userId);
6618        }
6619    }
6620
6621    @Override
6622    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6623            IntentFilter filter, int match, ComponentName activity) {
6624        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6625            return;
6626        }
6627        final int userId = UserHandle.getCallingUserId();
6628        if (DEBUG_PREFERRED) {
6629            Log.v(TAG, "setLastChosenActivity intent=" + intent
6630                + " resolvedType=" + resolvedType
6631                + " flags=" + flags
6632                + " filter=" + filter
6633                + " match=" + match
6634                + " activity=" + activity);
6635            filter.dump(new PrintStreamPrinter(System.out), "    ");
6636        }
6637        intent.setComponent(null);
6638        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6639                userId);
6640        // Find any earlier preferred or last chosen entries and nuke them
6641        findPreferredActivity(intent, resolvedType,
6642                flags, query, 0, false, true, false, userId);
6643        // Add the new activity as the last chosen for this filter
6644        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6645                "Setting last chosen");
6646    }
6647
6648    @Override
6649    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6650        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6651            return null;
6652        }
6653        final int userId = UserHandle.getCallingUserId();
6654        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6655        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6656                userId);
6657        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6658                false, false, false, userId);
6659    }
6660
6661    /**
6662     * Returns whether or not instant apps have been disabled remotely.
6663     */
6664    private boolean isEphemeralDisabled() {
6665        return mEphemeralAppsDisabled;
6666    }
6667
6668    private boolean isInstantAppAllowed(
6669            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6670            boolean skipPackageCheck) {
6671        if (mInstantAppResolverConnection == null) {
6672            return false;
6673        }
6674        if (mInstantAppInstallerActivity == null) {
6675            return false;
6676        }
6677        if (intent.getComponent() != null) {
6678            return false;
6679        }
6680        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6681            return false;
6682        }
6683        if (!skipPackageCheck && intent.getPackage() != null) {
6684            return false;
6685        }
6686        final boolean isWebUri = hasWebURI(intent);
6687        if (!isWebUri || intent.getData().getHost() == null) {
6688            return false;
6689        }
6690        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6691        // Or if there's already an ephemeral app installed that handles the action
6692        synchronized (mPackages) {
6693            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6694            for (int n = 0; n < count; n++) {
6695                final ResolveInfo info = resolvedActivities.get(n);
6696                final String packageName = info.activityInfo.packageName;
6697                final PackageSetting ps = mSettings.mPackages.get(packageName);
6698                if (ps != null) {
6699                    // only check domain verification status if the app is not a browser
6700                    if (!info.handleAllWebDataURI) {
6701                        // Try to get the status from User settings first
6702                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6703                        final int status = (int) (packedStatus >> 32);
6704                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6705                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6706                            if (DEBUG_EPHEMERAL) {
6707                                Slog.v(TAG, "DENY instant app;"
6708                                    + " pkg: " + packageName + ", status: " + status);
6709                            }
6710                            return false;
6711                        }
6712                    }
6713                    if (ps.getInstantApp(userId)) {
6714                        if (DEBUG_EPHEMERAL) {
6715                            Slog.v(TAG, "DENY instant app installed;"
6716                                    + " pkg: " + packageName);
6717                        }
6718                        return false;
6719                    }
6720                }
6721            }
6722        }
6723        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6724        return true;
6725    }
6726
6727    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6728            Intent origIntent, String resolvedType, String callingPackage,
6729            Bundle verificationBundle, int userId) {
6730        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6731                new InstantAppRequest(responseObj, origIntent, resolvedType,
6732                        callingPackage, userId, verificationBundle));
6733        mHandler.sendMessage(msg);
6734    }
6735
6736    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6737            int flags, List<ResolveInfo> query, int userId) {
6738        if (query != null) {
6739            final int N = query.size();
6740            if (N == 1) {
6741                return query.get(0);
6742            } else if (N > 1) {
6743                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6744                // If there is more than one activity with the same priority,
6745                // then let the user decide between them.
6746                ResolveInfo r0 = query.get(0);
6747                ResolveInfo r1 = query.get(1);
6748                if (DEBUG_INTENT_MATCHING || debug) {
6749                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6750                            + r1.activityInfo.name + "=" + r1.priority);
6751                }
6752                // If the first activity has a higher priority, or a different
6753                // default, then it is always desirable to pick it.
6754                if (r0.priority != r1.priority
6755                        || r0.preferredOrder != r1.preferredOrder
6756                        || r0.isDefault != r1.isDefault) {
6757                    return query.get(0);
6758                }
6759                // If we have saved a preference for a preferred activity for
6760                // this Intent, use that.
6761                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6762                        flags, query, r0.priority, true, false, debug, userId);
6763                if (ri != null) {
6764                    return ri;
6765                }
6766                // If we have an ephemeral app, use it
6767                for (int i = 0; i < N; i++) {
6768                    ri = query.get(i);
6769                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6770                        final String packageName = ri.activityInfo.packageName;
6771                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6772                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6773                        final int status = (int)(packedStatus >> 32);
6774                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6775                            return ri;
6776                        }
6777                    }
6778                }
6779                ri = new ResolveInfo(mResolveInfo);
6780                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6781                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6782                // If all of the options come from the same package, show the application's
6783                // label and icon instead of the generic resolver's.
6784                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6785                // and then throw away the ResolveInfo itself, meaning that the caller loses
6786                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6787                // a fallback for this case; we only set the target package's resources on
6788                // the ResolveInfo, not the ActivityInfo.
6789                final String intentPackage = intent.getPackage();
6790                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6791                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6792                    ri.resolvePackageName = intentPackage;
6793                    if (userNeedsBadging(userId)) {
6794                        ri.noResourceId = true;
6795                    } else {
6796                        ri.icon = appi.icon;
6797                    }
6798                    ri.iconResourceId = appi.icon;
6799                    ri.labelRes = appi.labelRes;
6800                }
6801                ri.activityInfo.applicationInfo = new ApplicationInfo(
6802                        ri.activityInfo.applicationInfo);
6803                if (userId != 0) {
6804                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6805                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6806                }
6807                // Make sure that the resolver is displayable in car mode
6808                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6809                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6810                return ri;
6811            }
6812        }
6813        return null;
6814    }
6815
6816    /**
6817     * Return true if the given list is not empty and all of its contents have
6818     * an activityInfo with the given package name.
6819     */
6820    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6821        if (ArrayUtils.isEmpty(list)) {
6822            return false;
6823        }
6824        for (int i = 0, N = list.size(); i < N; i++) {
6825            final ResolveInfo ri = list.get(i);
6826            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6827            if (ai == null || !packageName.equals(ai.packageName)) {
6828                return false;
6829            }
6830        }
6831        return true;
6832    }
6833
6834    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6835            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6836        final int N = query.size();
6837        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6838                .get(userId);
6839        // Get the list of persistent preferred activities that handle the intent
6840        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6841        List<PersistentPreferredActivity> pprefs = ppir != null
6842                ? ppir.queryIntent(intent, resolvedType,
6843                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6844                        userId)
6845                : null;
6846        if (pprefs != null && pprefs.size() > 0) {
6847            final int M = pprefs.size();
6848            for (int i=0; i<M; i++) {
6849                final PersistentPreferredActivity ppa = pprefs.get(i);
6850                if (DEBUG_PREFERRED || debug) {
6851                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6852                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6853                            + "\n  component=" + ppa.mComponent);
6854                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6855                }
6856                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6857                        flags | MATCH_DISABLED_COMPONENTS, userId);
6858                if (DEBUG_PREFERRED || debug) {
6859                    Slog.v(TAG, "Found persistent preferred activity:");
6860                    if (ai != null) {
6861                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6862                    } else {
6863                        Slog.v(TAG, "  null");
6864                    }
6865                }
6866                if (ai == null) {
6867                    // This previously registered persistent preferred activity
6868                    // component is no longer known. Ignore it and do NOT remove it.
6869                    continue;
6870                }
6871                for (int j=0; j<N; j++) {
6872                    final ResolveInfo ri = query.get(j);
6873                    if (!ri.activityInfo.applicationInfo.packageName
6874                            .equals(ai.applicationInfo.packageName)) {
6875                        continue;
6876                    }
6877                    if (!ri.activityInfo.name.equals(ai.name)) {
6878                        continue;
6879                    }
6880                    //  Found a persistent preference that can handle the intent.
6881                    if (DEBUG_PREFERRED || debug) {
6882                        Slog.v(TAG, "Returning persistent preferred activity: " +
6883                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6884                    }
6885                    return ri;
6886                }
6887            }
6888        }
6889        return null;
6890    }
6891
6892    // TODO: handle preferred activities missing while user has amnesia
6893    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6894            List<ResolveInfo> query, int priority, boolean always,
6895            boolean removeMatches, boolean debug, int userId) {
6896        if (!sUserManager.exists(userId)) return null;
6897        final int callingUid = Binder.getCallingUid();
6898        flags = updateFlagsForResolve(
6899                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6900        intent = updateIntentForResolve(intent);
6901        // writer
6902        synchronized (mPackages) {
6903            // Try to find a matching persistent preferred activity.
6904            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6905                    debug, userId);
6906
6907            // If a persistent preferred activity matched, use it.
6908            if (pri != null) {
6909                return pri;
6910            }
6911
6912            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6913            // Get the list of preferred activities that handle the intent
6914            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6915            List<PreferredActivity> prefs = pir != null
6916                    ? pir.queryIntent(intent, resolvedType,
6917                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6918                            userId)
6919                    : null;
6920            if (prefs != null && prefs.size() > 0) {
6921                boolean changed = false;
6922                try {
6923                    // First figure out how good the original match set is.
6924                    // We will only allow preferred activities that came
6925                    // from the same match quality.
6926                    int match = 0;
6927
6928                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6929
6930                    final int N = query.size();
6931                    for (int j=0; j<N; j++) {
6932                        final ResolveInfo ri = query.get(j);
6933                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6934                                + ": 0x" + Integer.toHexString(match));
6935                        if (ri.match > match) {
6936                            match = ri.match;
6937                        }
6938                    }
6939
6940                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6941                            + Integer.toHexString(match));
6942
6943                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6944                    final int M = prefs.size();
6945                    for (int i=0; i<M; i++) {
6946                        final PreferredActivity pa = prefs.get(i);
6947                        if (DEBUG_PREFERRED || debug) {
6948                            Slog.v(TAG, "Checking PreferredActivity ds="
6949                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6950                                    + "\n  component=" + pa.mPref.mComponent);
6951                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6952                        }
6953                        if (pa.mPref.mMatch != match) {
6954                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6955                                    + Integer.toHexString(pa.mPref.mMatch));
6956                            continue;
6957                        }
6958                        // If it's not an "always" type preferred activity and that's what we're
6959                        // looking for, skip it.
6960                        if (always && !pa.mPref.mAlways) {
6961                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6962                            continue;
6963                        }
6964                        final ActivityInfo ai = getActivityInfo(
6965                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6966                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6967                                userId);
6968                        if (DEBUG_PREFERRED || debug) {
6969                            Slog.v(TAG, "Found preferred activity:");
6970                            if (ai != null) {
6971                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6972                            } else {
6973                                Slog.v(TAG, "  null");
6974                            }
6975                        }
6976                        if (ai == null) {
6977                            // This previously registered preferred activity
6978                            // component is no longer known.  Most likely an update
6979                            // to the app was installed and in the new version this
6980                            // component no longer exists.  Clean it up by removing
6981                            // it from the preferred activities list, and skip it.
6982                            Slog.w(TAG, "Removing dangling preferred activity: "
6983                                    + pa.mPref.mComponent);
6984                            pir.removeFilter(pa);
6985                            changed = true;
6986                            continue;
6987                        }
6988                        for (int j=0; j<N; j++) {
6989                            final ResolveInfo ri = query.get(j);
6990                            if (!ri.activityInfo.applicationInfo.packageName
6991                                    .equals(ai.applicationInfo.packageName)) {
6992                                continue;
6993                            }
6994                            if (!ri.activityInfo.name.equals(ai.name)) {
6995                                continue;
6996                            }
6997
6998                            if (removeMatches) {
6999                                pir.removeFilter(pa);
7000                                changed = true;
7001                                if (DEBUG_PREFERRED) {
7002                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
7003                                }
7004                                break;
7005                            }
7006
7007                            // Okay we found a previously set preferred or last chosen app.
7008                            // If the result set is different from when this
7009                            // was created, we need to clear it and re-ask the
7010                            // user their preference, if we're looking for an "always" type entry.
7011                            if (always && !pa.mPref.sameSet(query)) {
7012                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
7013                                        + intent + " type " + resolvedType);
7014                                if (DEBUG_PREFERRED) {
7015                                    Slog.v(TAG, "Removing preferred activity since set changed "
7016                                            + pa.mPref.mComponent);
7017                                }
7018                                pir.removeFilter(pa);
7019                                // Re-add the filter as a "last chosen" entry (!always)
7020                                PreferredActivity lastChosen = new PreferredActivity(
7021                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
7022                                pir.addFilter(lastChosen);
7023                                changed = true;
7024                                return null;
7025                            }
7026
7027                            // Yay! Either the set matched or we're looking for the last chosen
7028                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
7029                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
7030                            return ri;
7031                        }
7032                    }
7033                } finally {
7034                    if (changed) {
7035                        if (DEBUG_PREFERRED) {
7036                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
7037                        }
7038                        scheduleWritePackageRestrictionsLocked(userId);
7039                    }
7040                }
7041            }
7042        }
7043        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
7044        return null;
7045    }
7046
7047    /*
7048     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
7049     */
7050    @Override
7051    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
7052            int targetUserId) {
7053        mContext.enforceCallingOrSelfPermission(
7054                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
7055        List<CrossProfileIntentFilter> matches =
7056                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
7057        if (matches != null) {
7058            int size = matches.size();
7059            for (int i = 0; i < size; i++) {
7060                if (matches.get(i).getTargetUserId() == targetUserId) return true;
7061            }
7062        }
7063        if (hasWebURI(intent)) {
7064            // cross-profile app linking works only towards the parent.
7065            final int callingUid = Binder.getCallingUid();
7066            final UserInfo parent = getProfileParent(sourceUserId);
7067            synchronized(mPackages) {
7068                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
7069                        false /*includeInstantApps*/);
7070                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
7071                        intent, resolvedType, flags, sourceUserId, parent.id);
7072                return xpDomainInfo != null;
7073            }
7074        }
7075        return false;
7076    }
7077
7078    private UserInfo getProfileParent(int userId) {
7079        final long identity = Binder.clearCallingIdentity();
7080        try {
7081            return sUserManager.getProfileParent(userId);
7082        } finally {
7083            Binder.restoreCallingIdentity(identity);
7084        }
7085    }
7086
7087    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
7088            String resolvedType, int userId) {
7089        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
7090        if (resolver != null) {
7091            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
7092        }
7093        return null;
7094    }
7095
7096    @Override
7097    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
7098            String resolvedType, int flags, int userId) {
7099        try {
7100            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
7101
7102            return new ParceledListSlice<>(
7103                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
7104        } finally {
7105            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7106        }
7107    }
7108
7109    /**
7110     * Returns the package name of the calling Uid if it's an instant app. If it isn't
7111     * instant, returns {@code null}.
7112     */
7113    private String getInstantAppPackageName(int callingUid) {
7114        synchronized (mPackages) {
7115            // If the caller is an isolated app use the owner's uid for the lookup.
7116            if (Process.isIsolated(callingUid)) {
7117                callingUid = mIsolatedOwners.get(callingUid);
7118            }
7119            final int appId = UserHandle.getAppId(callingUid);
7120            final Object obj = mSettings.getUserIdLPr(appId);
7121            if (obj instanceof PackageSetting) {
7122                final PackageSetting ps = (PackageSetting) obj;
7123                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
7124                return isInstantApp ? ps.pkg.packageName : null;
7125            }
7126        }
7127        return null;
7128    }
7129
7130    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7131            String resolvedType, int flags, int userId) {
7132        return queryIntentActivitiesInternal(
7133                intent, resolvedType, flags, Binder.getCallingUid(), userId, false);
7134    }
7135
7136    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7137            String resolvedType, int flags, int filterCallingUid, int userId,
7138            boolean resolveForStart) {
7139        if (!sUserManager.exists(userId)) return Collections.emptyList();
7140        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
7141        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7142                false /* requireFullPermission */, false /* checkShell */,
7143                "query intent activities");
7144        final String pkgName = intent.getPackage();
7145        ComponentName comp = intent.getComponent();
7146        if (comp == null) {
7147            if (intent.getSelector() != null) {
7148                intent = intent.getSelector();
7149                comp = intent.getComponent();
7150            }
7151        }
7152
7153        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
7154                comp != null || pkgName != null /*onlyExposedExplicitly*/);
7155        if (comp != null) {
7156            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7157            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
7158            if (ai != null) {
7159                // When specifying an explicit component, we prevent the activity from being
7160                // used when either 1) the calling package is normal and the activity is within
7161                // an ephemeral application or 2) the calling package is ephemeral and the
7162                // activity is not visible to ephemeral applications.
7163                final boolean matchInstantApp =
7164                        (flags & PackageManager.MATCH_INSTANT) != 0;
7165                final boolean matchVisibleToInstantAppOnly =
7166                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7167                final boolean matchExplicitlyVisibleOnly =
7168                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7169                final boolean isCallerInstantApp =
7170                        instantAppPkgName != null;
7171                final boolean isTargetSameInstantApp =
7172                        comp.getPackageName().equals(instantAppPkgName);
7173                final boolean isTargetInstantApp =
7174                        (ai.applicationInfo.privateFlags
7175                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7176                final boolean isTargetVisibleToInstantApp =
7177                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7178                final boolean isTargetExplicitlyVisibleToInstantApp =
7179                        isTargetVisibleToInstantApp
7180                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7181                final boolean isTargetHiddenFromInstantApp =
7182                        !isTargetVisibleToInstantApp
7183                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7184                final boolean blockResolution =
7185                        !isTargetSameInstantApp
7186                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7187                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7188                                        && isTargetHiddenFromInstantApp));
7189                if (!blockResolution) {
7190                    final ResolveInfo ri = new ResolveInfo();
7191                    ri.activityInfo = ai;
7192                    list.add(ri);
7193                }
7194            }
7195            return applyPostResolutionFilter(list, instantAppPkgName);
7196        }
7197
7198        // reader
7199        boolean sortResult = false;
7200        boolean addEphemeral = false;
7201        List<ResolveInfo> result;
7202        final boolean ephemeralDisabled = isEphemeralDisabled();
7203        synchronized (mPackages) {
7204            if (pkgName == null) {
7205                List<CrossProfileIntentFilter> matchingFilters =
7206                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
7207                // Check for results that need to skip the current profile.
7208                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
7209                        resolvedType, flags, userId);
7210                if (xpResolveInfo != null) {
7211                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
7212                    xpResult.add(xpResolveInfo);
7213                    return applyPostResolutionFilter(
7214                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
7215                }
7216
7217                // Check for results in the current profile.
7218                result = filterIfNotSystemUser(mActivities.queryIntent(
7219                        intent, resolvedType, flags, userId), userId);
7220                addEphemeral = !ephemeralDisabled
7221                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
7222                // Check for cross profile results.
7223                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
7224                xpResolveInfo = queryCrossProfileIntents(
7225                        matchingFilters, intent, resolvedType, flags, userId,
7226                        hasNonNegativePriorityResult);
7227                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
7228                    boolean isVisibleToUser = filterIfNotSystemUser(
7229                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
7230                    if (isVisibleToUser) {
7231                        result.add(xpResolveInfo);
7232                        sortResult = true;
7233                    }
7234                }
7235                if (hasWebURI(intent)) {
7236                    CrossProfileDomainInfo xpDomainInfo = null;
7237                    final UserInfo parent = getProfileParent(userId);
7238                    if (parent != null) {
7239                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
7240                                flags, userId, parent.id);
7241                    }
7242                    if (xpDomainInfo != null) {
7243                        if (xpResolveInfo != null) {
7244                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
7245                            // in the result.
7246                            result.remove(xpResolveInfo);
7247                        }
7248                        if (result.size() == 0 && !addEphemeral) {
7249                            // No result in current profile, but found candidate in parent user.
7250                            // And we are not going to add emphemeral app, so we can return the
7251                            // result straight away.
7252                            result.add(xpDomainInfo.resolveInfo);
7253                            return applyPostResolutionFilter(result, instantAppPkgName);
7254                        }
7255                    } else if (result.size() <= 1 && !addEphemeral) {
7256                        // No result in parent user and <= 1 result in current profile, and we
7257                        // are not going to add emphemeral app, so we can return the result without
7258                        // further processing.
7259                        return applyPostResolutionFilter(result, instantAppPkgName);
7260                    }
7261                    // We have more than one candidate (combining results from current and parent
7262                    // profile), so we need filtering and sorting.
7263                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
7264                            intent, flags, result, xpDomainInfo, userId);
7265                    sortResult = true;
7266                }
7267            } else {
7268                final PackageParser.Package pkg = mPackages.get(pkgName);
7269                result = null;
7270                if (pkg != null) {
7271                    result = filterIfNotSystemUser(
7272                            mActivities.queryIntentForPackage(
7273                                    intent, resolvedType, flags, pkg.activities, userId),
7274                            userId);
7275                }
7276                if (result == null || result.size() == 0) {
7277                    // the caller wants to resolve for a particular package; however, there
7278                    // were no installed results, so, try to find an ephemeral result
7279                    addEphemeral = !ephemeralDisabled
7280                            && isInstantAppAllowed(
7281                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
7282                    if (result == null) {
7283                        result = new ArrayList<>();
7284                    }
7285                }
7286            }
7287        }
7288        if (addEphemeral) {
7289            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
7290        }
7291        if (sortResult) {
7292            Collections.sort(result, mResolvePrioritySorter);
7293        }
7294        return applyPostResolutionFilter(result, instantAppPkgName);
7295    }
7296
7297    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7298            String resolvedType, int flags, int userId) {
7299        // first, check to see if we've got an instant app already installed
7300        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7301        ResolveInfo localInstantApp = null;
7302        boolean blockResolution = false;
7303        if (!alreadyResolvedLocally) {
7304            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7305                    flags
7306                        | PackageManager.GET_RESOLVED_FILTER
7307                        | PackageManager.MATCH_INSTANT
7308                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7309                    userId);
7310            for (int i = instantApps.size() - 1; i >= 0; --i) {
7311                final ResolveInfo info = instantApps.get(i);
7312                final String packageName = info.activityInfo.packageName;
7313                final PackageSetting ps = mSettings.mPackages.get(packageName);
7314                if (ps.getInstantApp(userId)) {
7315                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7316                    final int status = (int)(packedStatus >> 32);
7317                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7318                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7319                        // there's a local instant application installed, but, the user has
7320                        // chosen to never use it; skip resolution and don't acknowledge
7321                        // an instant application is even available
7322                        if (DEBUG_EPHEMERAL) {
7323                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7324                        }
7325                        blockResolution = true;
7326                        break;
7327                    } else {
7328                        // we have a locally installed instant application; skip resolution
7329                        // but acknowledge there's an instant application available
7330                        if (DEBUG_EPHEMERAL) {
7331                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7332                        }
7333                        localInstantApp = info;
7334                        break;
7335                    }
7336                }
7337            }
7338        }
7339        // no app installed, let's see if one's available
7340        AuxiliaryResolveInfo auxiliaryResponse = null;
7341        if (!blockResolution) {
7342            if (localInstantApp == null) {
7343                // we don't have an instant app locally, resolve externally
7344                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7345                final InstantAppRequest requestObject = new InstantAppRequest(
7346                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7347                        null /*callingPackage*/, userId, null /*verificationBundle*/);
7348                auxiliaryResponse =
7349                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7350                                mContext, mInstantAppResolverConnection, requestObject);
7351                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7352            } else {
7353                // we have an instant application locally, but, we can't admit that since
7354                // callers shouldn't be able to determine prior browsing. create a dummy
7355                // auxiliary response so the downstream code behaves as if there's an
7356                // instant application available externally. when it comes time to start
7357                // the instant application, we'll do the right thing.
7358                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7359                auxiliaryResponse = new AuxiliaryResolveInfo(
7360                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
7361            }
7362        }
7363        if (auxiliaryResponse != null) {
7364            if (DEBUG_EPHEMERAL) {
7365                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7366            }
7367            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7368            final PackageSetting ps =
7369                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7370            if (ps != null) {
7371                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7372                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7373                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7374                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7375                // make sure this resolver is the default
7376                ephemeralInstaller.isDefault = true;
7377                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7378                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7379                // add a non-generic filter
7380                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7381                ephemeralInstaller.filter.addDataPath(
7382                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7383                ephemeralInstaller.isInstantAppAvailable = true;
7384                result.add(ephemeralInstaller);
7385            }
7386        }
7387        return result;
7388    }
7389
7390    private static class CrossProfileDomainInfo {
7391        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7392        ResolveInfo resolveInfo;
7393        /* Best domain verification status of the activities found in the other profile */
7394        int bestDomainVerificationStatus;
7395    }
7396
7397    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7398            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7399        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7400                sourceUserId)) {
7401            return null;
7402        }
7403        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7404                resolvedType, flags, parentUserId);
7405
7406        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7407            return null;
7408        }
7409        CrossProfileDomainInfo result = null;
7410        int size = resultTargetUser.size();
7411        for (int i = 0; i < size; i++) {
7412            ResolveInfo riTargetUser = resultTargetUser.get(i);
7413            // Intent filter verification is only for filters that specify a host. So don't return
7414            // those that handle all web uris.
7415            if (riTargetUser.handleAllWebDataURI) {
7416                continue;
7417            }
7418            String packageName = riTargetUser.activityInfo.packageName;
7419            PackageSetting ps = mSettings.mPackages.get(packageName);
7420            if (ps == null) {
7421                continue;
7422            }
7423            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7424            int status = (int)(verificationState >> 32);
7425            if (result == null) {
7426                result = new CrossProfileDomainInfo();
7427                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7428                        sourceUserId, parentUserId);
7429                result.bestDomainVerificationStatus = status;
7430            } else {
7431                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7432                        result.bestDomainVerificationStatus);
7433            }
7434        }
7435        // Don't consider matches with status NEVER across profiles.
7436        if (result != null && result.bestDomainVerificationStatus
7437                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7438            return null;
7439        }
7440        return result;
7441    }
7442
7443    /**
7444     * Verification statuses are ordered from the worse to the best, except for
7445     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7446     */
7447    private int bestDomainVerificationStatus(int status1, int status2) {
7448        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7449            return status2;
7450        }
7451        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7452            return status1;
7453        }
7454        return (int) MathUtils.max(status1, status2);
7455    }
7456
7457    private boolean isUserEnabled(int userId) {
7458        long callingId = Binder.clearCallingIdentity();
7459        try {
7460            UserInfo userInfo = sUserManager.getUserInfo(userId);
7461            return userInfo != null && userInfo.isEnabled();
7462        } finally {
7463            Binder.restoreCallingIdentity(callingId);
7464        }
7465    }
7466
7467    /**
7468     * Filter out activities with systemUserOnly flag set, when current user is not System.
7469     *
7470     * @return filtered list
7471     */
7472    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7473        if (userId == UserHandle.USER_SYSTEM) {
7474            return resolveInfos;
7475        }
7476        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7477            ResolveInfo info = resolveInfos.get(i);
7478            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7479                resolveInfos.remove(i);
7480            }
7481        }
7482        return resolveInfos;
7483    }
7484
7485    /**
7486     * Filters out ephemeral activities.
7487     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7488     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7489     *
7490     * @param resolveInfos The pre-filtered list of resolved activities
7491     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7492     *          is performed.
7493     * @return A filtered list of resolved activities.
7494     */
7495    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7496            String ephemeralPkgName) {
7497        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7498            final ResolveInfo info = resolveInfos.get(i);
7499            // TODO: When adding on-demand split support for non-instant apps, remove this check
7500            // and always apply post filtering
7501            // allow activities that are defined in the provided package
7502            if (info.activityInfo.splitName != null
7503                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7504                            info.activityInfo.splitName)) {
7505                // requested activity is defined in a split that hasn't been installed yet.
7506                // add the installer to the resolve list
7507                if (DEBUG_INSTALL) {
7508                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
7509                }
7510                final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7511                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7512                        info.activityInfo.packageName, info.activityInfo.splitName,
7513                        info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
7514                // make sure this resolver is the default
7515                installerInfo.isDefault = true;
7516                installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7517                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7518                // add a non-generic filter
7519                installerInfo.filter = new IntentFilter();
7520                // load resources from the correct package
7521                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7522                resolveInfos.set(i, installerInfo);
7523                continue;
7524            }
7525            // caller is a full app, don't need to apply any other filtering
7526            if (ephemeralPkgName == null) {
7527                continue;
7528            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7529                // caller is same app; don't need to apply any other filtering
7530                continue;
7531            }
7532            // allow activities that have been explicitly exposed to ephemeral apps
7533            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7534            if (!isEphemeralApp
7535                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7536                continue;
7537            }
7538            resolveInfos.remove(i);
7539        }
7540        return resolveInfos;
7541    }
7542
7543    /**
7544     * @param resolveInfos list of resolve infos in descending priority order
7545     * @return if the list contains a resolve info with non-negative priority
7546     */
7547    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7548        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7549    }
7550
7551    private static boolean hasWebURI(Intent intent) {
7552        if (intent.getData() == null) {
7553            return false;
7554        }
7555        final String scheme = intent.getScheme();
7556        if (TextUtils.isEmpty(scheme)) {
7557            return false;
7558        }
7559        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7560    }
7561
7562    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7563            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7564            int userId) {
7565        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7566
7567        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7568            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7569                    candidates.size());
7570        }
7571
7572        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7573        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7574        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7575        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7576        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7577        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7578
7579        synchronized (mPackages) {
7580            final int count = candidates.size();
7581            // First, try to use linked apps. Partition the candidates into four lists:
7582            // one for the final results, one for the "do not use ever", one for "undefined status"
7583            // and finally one for "browser app type".
7584            for (int n=0; n<count; n++) {
7585                ResolveInfo info = candidates.get(n);
7586                String packageName = info.activityInfo.packageName;
7587                PackageSetting ps = mSettings.mPackages.get(packageName);
7588                if (ps != null) {
7589                    // Add to the special match all list (Browser use case)
7590                    if (info.handleAllWebDataURI) {
7591                        matchAllList.add(info);
7592                        continue;
7593                    }
7594                    // Try to get the status from User settings first
7595                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7596                    int status = (int)(packedStatus >> 32);
7597                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7598                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7599                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7600                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7601                                    + " : linkgen=" + linkGeneration);
7602                        }
7603                        // Use link-enabled generation as preferredOrder, i.e.
7604                        // prefer newly-enabled over earlier-enabled.
7605                        info.preferredOrder = linkGeneration;
7606                        alwaysList.add(info);
7607                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7608                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7609                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7610                        }
7611                        neverList.add(info);
7612                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7613                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7614                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7615                        }
7616                        alwaysAskList.add(info);
7617                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7618                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7619                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7620                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7621                        }
7622                        undefinedList.add(info);
7623                    }
7624                }
7625            }
7626
7627            // We'll want to include browser possibilities in a few cases
7628            boolean includeBrowser = false;
7629
7630            // First try to add the "always" resolution(s) for the current user, if any
7631            if (alwaysList.size() > 0) {
7632                result.addAll(alwaysList);
7633            } else {
7634                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7635                result.addAll(undefinedList);
7636                // Maybe add one for the other profile.
7637                if (xpDomainInfo != null && (
7638                        xpDomainInfo.bestDomainVerificationStatus
7639                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7640                    result.add(xpDomainInfo.resolveInfo);
7641                }
7642                includeBrowser = true;
7643            }
7644
7645            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7646            // If there were 'always' entries their preferred order has been set, so we also
7647            // back that off to make the alternatives equivalent
7648            if (alwaysAskList.size() > 0) {
7649                for (ResolveInfo i : result) {
7650                    i.preferredOrder = 0;
7651                }
7652                result.addAll(alwaysAskList);
7653                includeBrowser = true;
7654            }
7655
7656            if (includeBrowser) {
7657                // Also add browsers (all of them or only the default one)
7658                if (DEBUG_DOMAIN_VERIFICATION) {
7659                    Slog.v(TAG, "   ...including browsers in candidate set");
7660                }
7661                if ((matchFlags & MATCH_ALL) != 0) {
7662                    result.addAll(matchAllList);
7663                } else {
7664                    // Browser/generic handling case.  If there's a default browser, go straight
7665                    // to that (but only if there is no other higher-priority match).
7666                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7667                    int maxMatchPrio = 0;
7668                    ResolveInfo defaultBrowserMatch = null;
7669                    final int numCandidates = matchAllList.size();
7670                    for (int n = 0; n < numCandidates; n++) {
7671                        ResolveInfo info = matchAllList.get(n);
7672                        // track the highest overall match priority...
7673                        if (info.priority > maxMatchPrio) {
7674                            maxMatchPrio = info.priority;
7675                        }
7676                        // ...and the highest-priority default browser match
7677                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7678                            if (defaultBrowserMatch == null
7679                                    || (defaultBrowserMatch.priority < info.priority)) {
7680                                if (debug) {
7681                                    Slog.v(TAG, "Considering default browser match " + info);
7682                                }
7683                                defaultBrowserMatch = info;
7684                            }
7685                        }
7686                    }
7687                    if (defaultBrowserMatch != null
7688                            && defaultBrowserMatch.priority >= maxMatchPrio
7689                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7690                    {
7691                        if (debug) {
7692                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7693                        }
7694                        result.add(defaultBrowserMatch);
7695                    } else {
7696                        result.addAll(matchAllList);
7697                    }
7698                }
7699
7700                // If there is nothing selected, add all candidates and remove the ones that the user
7701                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7702                if (result.size() == 0) {
7703                    result.addAll(candidates);
7704                    result.removeAll(neverList);
7705                }
7706            }
7707        }
7708        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7709            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7710                    result.size());
7711            for (ResolveInfo info : result) {
7712                Slog.v(TAG, "  + " + info.activityInfo);
7713            }
7714        }
7715        return result;
7716    }
7717
7718    // Returns a packed value as a long:
7719    //
7720    // high 'int'-sized word: link status: undefined/ask/never/always.
7721    // low 'int'-sized word: relative priority among 'always' results.
7722    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7723        long result = ps.getDomainVerificationStatusForUser(userId);
7724        // if none available, get the master status
7725        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7726            if (ps.getIntentFilterVerificationInfo() != null) {
7727                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7728            }
7729        }
7730        return result;
7731    }
7732
7733    private ResolveInfo querySkipCurrentProfileIntents(
7734            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7735            int flags, int sourceUserId) {
7736        if (matchingFilters != null) {
7737            int size = matchingFilters.size();
7738            for (int i = 0; i < size; i ++) {
7739                CrossProfileIntentFilter filter = matchingFilters.get(i);
7740                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7741                    // Checking if there are activities in the target user that can handle the
7742                    // intent.
7743                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7744                            resolvedType, flags, sourceUserId);
7745                    if (resolveInfo != null) {
7746                        return resolveInfo;
7747                    }
7748                }
7749            }
7750        }
7751        return null;
7752    }
7753
7754    // Return matching ResolveInfo in target user if any.
7755    private ResolveInfo queryCrossProfileIntents(
7756            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7757            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7758        if (matchingFilters != null) {
7759            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7760            // match the same intent. For performance reasons, it is better not to
7761            // run queryIntent twice for the same userId
7762            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7763            int size = matchingFilters.size();
7764            for (int i = 0; i < size; i++) {
7765                CrossProfileIntentFilter filter = matchingFilters.get(i);
7766                int targetUserId = filter.getTargetUserId();
7767                boolean skipCurrentProfile =
7768                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7769                boolean skipCurrentProfileIfNoMatchFound =
7770                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7771                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7772                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7773                    // Checking if there are activities in the target user that can handle the
7774                    // intent.
7775                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7776                            resolvedType, flags, sourceUserId);
7777                    if (resolveInfo != null) return resolveInfo;
7778                    alreadyTriedUserIds.put(targetUserId, true);
7779                }
7780            }
7781        }
7782        return null;
7783    }
7784
7785    /**
7786     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7787     * will forward the intent to the filter's target user.
7788     * Otherwise, returns null.
7789     */
7790    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7791            String resolvedType, int flags, int sourceUserId) {
7792        int targetUserId = filter.getTargetUserId();
7793        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7794                resolvedType, flags, targetUserId);
7795        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7796            // If all the matches in the target profile are suspended, return null.
7797            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7798                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7799                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7800                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7801                            targetUserId);
7802                }
7803            }
7804        }
7805        return null;
7806    }
7807
7808    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7809            int sourceUserId, int targetUserId) {
7810        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7811        long ident = Binder.clearCallingIdentity();
7812        boolean targetIsProfile;
7813        try {
7814            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7815        } finally {
7816            Binder.restoreCallingIdentity(ident);
7817        }
7818        String className;
7819        if (targetIsProfile) {
7820            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7821        } else {
7822            className = FORWARD_INTENT_TO_PARENT;
7823        }
7824        ComponentName forwardingActivityComponentName = new ComponentName(
7825                mAndroidApplication.packageName, className);
7826        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7827                sourceUserId);
7828        if (!targetIsProfile) {
7829            forwardingActivityInfo.showUserIcon = targetUserId;
7830            forwardingResolveInfo.noResourceId = true;
7831        }
7832        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7833        forwardingResolveInfo.priority = 0;
7834        forwardingResolveInfo.preferredOrder = 0;
7835        forwardingResolveInfo.match = 0;
7836        forwardingResolveInfo.isDefault = true;
7837        forwardingResolveInfo.filter = filter;
7838        forwardingResolveInfo.targetUserId = targetUserId;
7839        return forwardingResolveInfo;
7840    }
7841
7842    @Override
7843    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7844            Intent[] specifics, String[] specificTypes, Intent intent,
7845            String resolvedType, int flags, int userId) {
7846        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7847                specificTypes, intent, resolvedType, flags, userId));
7848    }
7849
7850    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7851            Intent[] specifics, String[] specificTypes, Intent intent,
7852            String resolvedType, int flags, int userId) {
7853        if (!sUserManager.exists(userId)) return Collections.emptyList();
7854        final int callingUid = Binder.getCallingUid();
7855        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7856                false /*includeInstantApps*/);
7857        enforceCrossUserPermission(callingUid, userId,
7858                false /*requireFullPermission*/, false /*checkShell*/,
7859                "query intent activity options");
7860        final String resultsAction = intent.getAction();
7861
7862        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7863                | PackageManager.GET_RESOLVED_FILTER, userId);
7864
7865        if (DEBUG_INTENT_MATCHING) {
7866            Log.v(TAG, "Query " + intent + ": " + results);
7867        }
7868
7869        int specificsPos = 0;
7870        int N;
7871
7872        // todo: note that the algorithm used here is O(N^2).  This
7873        // isn't a problem in our current environment, but if we start running
7874        // into situations where we have more than 5 or 10 matches then this
7875        // should probably be changed to something smarter...
7876
7877        // First we go through and resolve each of the specific items
7878        // that were supplied, taking care of removing any corresponding
7879        // duplicate items in the generic resolve list.
7880        if (specifics != null) {
7881            for (int i=0; i<specifics.length; i++) {
7882                final Intent sintent = specifics[i];
7883                if (sintent == null) {
7884                    continue;
7885                }
7886
7887                if (DEBUG_INTENT_MATCHING) {
7888                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7889                }
7890
7891                String action = sintent.getAction();
7892                if (resultsAction != null && resultsAction.equals(action)) {
7893                    // If this action was explicitly requested, then don't
7894                    // remove things that have it.
7895                    action = null;
7896                }
7897
7898                ResolveInfo ri = null;
7899                ActivityInfo ai = null;
7900
7901                ComponentName comp = sintent.getComponent();
7902                if (comp == null) {
7903                    ri = resolveIntent(
7904                        sintent,
7905                        specificTypes != null ? specificTypes[i] : null,
7906                            flags, userId);
7907                    if (ri == null) {
7908                        continue;
7909                    }
7910                    if (ri == mResolveInfo) {
7911                        // ACK!  Must do something better with this.
7912                    }
7913                    ai = ri.activityInfo;
7914                    comp = new ComponentName(ai.applicationInfo.packageName,
7915                            ai.name);
7916                } else {
7917                    ai = getActivityInfo(comp, flags, userId);
7918                    if (ai == null) {
7919                        continue;
7920                    }
7921                }
7922
7923                // Look for any generic query activities that are duplicates
7924                // of this specific one, and remove them from the results.
7925                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7926                N = results.size();
7927                int j;
7928                for (j=specificsPos; j<N; j++) {
7929                    ResolveInfo sri = results.get(j);
7930                    if ((sri.activityInfo.name.equals(comp.getClassName())
7931                            && sri.activityInfo.applicationInfo.packageName.equals(
7932                                    comp.getPackageName()))
7933                        || (action != null && sri.filter.matchAction(action))) {
7934                        results.remove(j);
7935                        if (DEBUG_INTENT_MATCHING) Log.v(
7936                            TAG, "Removing duplicate item from " + j
7937                            + " due to specific " + specificsPos);
7938                        if (ri == null) {
7939                            ri = sri;
7940                        }
7941                        j--;
7942                        N--;
7943                    }
7944                }
7945
7946                // Add this specific item to its proper place.
7947                if (ri == null) {
7948                    ri = new ResolveInfo();
7949                    ri.activityInfo = ai;
7950                }
7951                results.add(specificsPos, ri);
7952                ri.specificIndex = i;
7953                specificsPos++;
7954            }
7955        }
7956
7957        // Now we go through the remaining generic results and remove any
7958        // duplicate actions that are found here.
7959        N = results.size();
7960        for (int i=specificsPos; i<N-1; i++) {
7961            final ResolveInfo rii = results.get(i);
7962            if (rii.filter == null) {
7963                continue;
7964            }
7965
7966            // Iterate over all of the actions of this result's intent
7967            // filter...  typically this should be just one.
7968            final Iterator<String> it = rii.filter.actionsIterator();
7969            if (it == null) {
7970                continue;
7971            }
7972            while (it.hasNext()) {
7973                final String action = it.next();
7974                if (resultsAction != null && resultsAction.equals(action)) {
7975                    // If this action was explicitly requested, then don't
7976                    // remove things that have it.
7977                    continue;
7978                }
7979                for (int j=i+1; j<N; j++) {
7980                    final ResolveInfo rij = results.get(j);
7981                    if (rij.filter != null && rij.filter.hasAction(action)) {
7982                        results.remove(j);
7983                        if (DEBUG_INTENT_MATCHING) Log.v(
7984                            TAG, "Removing duplicate item from " + j
7985                            + " due to action " + action + " at " + i);
7986                        j--;
7987                        N--;
7988                    }
7989                }
7990            }
7991
7992            // If the caller didn't request filter information, drop it now
7993            // so we don't have to marshall/unmarshall it.
7994            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7995                rii.filter = null;
7996            }
7997        }
7998
7999        // Filter out the caller activity if so requested.
8000        if (caller != null) {
8001            N = results.size();
8002            for (int i=0; i<N; i++) {
8003                ActivityInfo ainfo = results.get(i).activityInfo;
8004                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
8005                        && caller.getClassName().equals(ainfo.name)) {
8006                    results.remove(i);
8007                    break;
8008                }
8009            }
8010        }
8011
8012        // If the caller didn't request filter information,
8013        // drop them now so we don't have to
8014        // marshall/unmarshall it.
8015        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8016            N = results.size();
8017            for (int i=0; i<N; i++) {
8018                results.get(i).filter = null;
8019            }
8020        }
8021
8022        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
8023        return results;
8024    }
8025
8026    @Override
8027    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
8028            String resolvedType, int flags, int userId) {
8029        return new ParceledListSlice<>(
8030                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
8031    }
8032
8033    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
8034            String resolvedType, int flags, int userId) {
8035        if (!sUserManager.exists(userId)) return Collections.emptyList();
8036        final int callingUid = Binder.getCallingUid();
8037        enforceCrossUserPermission(callingUid, userId,
8038                false /*requireFullPermission*/, false /*checkShell*/,
8039                "query intent receivers");
8040        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8041        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8042                false /*includeInstantApps*/);
8043        ComponentName comp = intent.getComponent();
8044        if (comp == null) {
8045            if (intent.getSelector() != null) {
8046                intent = intent.getSelector();
8047                comp = intent.getComponent();
8048            }
8049        }
8050        if (comp != null) {
8051            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8052            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
8053            if (ai != null) {
8054                // When specifying an explicit component, we prevent the activity from being
8055                // used when either 1) the calling package is normal and the activity is within
8056                // an instant application or 2) the calling package is ephemeral and the
8057                // activity is not visible to instant applications.
8058                final boolean matchInstantApp =
8059                        (flags & PackageManager.MATCH_INSTANT) != 0;
8060                final boolean matchVisibleToInstantAppOnly =
8061                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8062                final boolean matchExplicitlyVisibleOnly =
8063                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
8064                final boolean isCallerInstantApp =
8065                        instantAppPkgName != null;
8066                final boolean isTargetSameInstantApp =
8067                        comp.getPackageName().equals(instantAppPkgName);
8068                final boolean isTargetInstantApp =
8069                        (ai.applicationInfo.privateFlags
8070                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8071                final boolean isTargetVisibleToInstantApp =
8072                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
8073                final boolean isTargetExplicitlyVisibleToInstantApp =
8074                        isTargetVisibleToInstantApp
8075                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
8076                final boolean isTargetHiddenFromInstantApp =
8077                        !isTargetVisibleToInstantApp
8078                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
8079                final boolean blockResolution =
8080                        !isTargetSameInstantApp
8081                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8082                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8083                                        && isTargetHiddenFromInstantApp));
8084                if (!blockResolution) {
8085                    ResolveInfo ri = new ResolveInfo();
8086                    ri.activityInfo = ai;
8087                    list.add(ri);
8088                }
8089            }
8090            return applyPostResolutionFilter(list, instantAppPkgName);
8091        }
8092
8093        // reader
8094        synchronized (mPackages) {
8095            String pkgName = intent.getPackage();
8096            if (pkgName == null) {
8097                final List<ResolveInfo> result =
8098                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
8099                return applyPostResolutionFilter(result, instantAppPkgName);
8100            }
8101            final PackageParser.Package pkg = mPackages.get(pkgName);
8102            if (pkg != null) {
8103                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
8104                        intent, resolvedType, flags, pkg.receivers, userId);
8105                return applyPostResolutionFilter(result, instantAppPkgName);
8106            }
8107            return Collections.emptyList();
8108        }
8109    }
8110
8111    @Override
8112    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
8113        final int callingUid = Binder.getCallingUid();
8114        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
8115    }
8116
8117    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
8118            int userId, int callingUid) {
8119        if (!sUserManager.exists(userId)) return null;
8120        flags = updateFlagsForResolve(
8121                flags, userId, intent, callingUid, false /*includeInstantApps*/);
8122        List<ResolveInfo> query = queryIntentServicesInternal(
8123                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
8124        if (query != null) {
8125            if (query.size() >= 1) {
8126                // If there is more than one service with the same priority,
8127                // just arbitrarily pick the first one.
8128                return query.get(0);
8129            }
8130        }
8131        return null;
8132    }
8133
8134    @Override
8135    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
8136            String resolvedType, int flags, int userId) {
8137        final int callingUid = Binder.getCallingUid();
8138        return new ParceledListSlice<>(queryIntentServicesInternal(
8139                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
8140    }
8141
8142    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
8143            String resolvedType, int flags, int userId, int callingUid,
8144            boolean includeInstantApps) {
8145        if (!sUserManager.exists(userId)) return Collections.emptyList();
8146        enforceCrossUserPermission(callingUid, userId,
8147                false /*requireFullPermission*/, false /*checkShell*/,
8148                "query intent receivers");
8149        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8150        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
8151        ComponentName comp = intent.getComponent();
8152        if (comp == null) {
8153            if (intent.getSelector() != null) {
8154                intent = intent.getSelector();
8155                comp = intent.getComponent();
8156            }
8157        }
8158        if (comp != null) {
8159            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8160            final ServiceInfo si = getServiceInfo(comp, flags, userId);
8161            if (si != null) {
8162                // When specifying an explicit component, we prevent the service from being
8163                // used when either 1) the service is in an instant application and the
8164                // caller is not the same instant application or 2) the calling package is
8165                // ephemeral and the activity is not visible to ephemeral applications.
8166                final boolean matchInstantApp =
8167                        (flags & PackageManager.MATCH_INSTANT) != 0;
8168                final boolean matchVisibleToInstantAppOnly =
8169                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8170                final boolean isCallerInstantApp =
8171                        instantAppPkgName != null;
8172                final boolean isTargetSameInstantApp =
8173                        comp.getPackageName().equals(instantAppPkgName);
8174                final boolean isTargetInstantApp =
8175                        (si.applicationInfo.privateFlags
8176                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8177                final boolean isTargetHiddenFromInstantApp =
8178                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8179                final boolean blockResolution =
8180                        !isTargetSameInstantApp
8181                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8182                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8183                                        && isTargetHiddenFromInstantApp));
8184                if (!blockResolution) {
8185                    final ResolveInfo ri = new ResolveInfo();
8186                    ri.serviceInfo = si;
8187                    list.add(ri);
8188                }
8189            }
8190            return list;
8191        }
8192
8193        // reader
8194        synchronized (mPackages) {
8195            String pkgName = intent.getPackage();
8196            if (pkgName == null) {
8197                return applyPostServiceResolutionFilter(
8198                        mServices.queryIntent(intent, resolvedType, flags, userId),
8199                        instantAppPkgName);
8200            }
8201            final PackageParser.Package pkg = mPackages.get(pkgName);
8202            if (pkg != null) {
8203                return applyPostServiceResolutionFilter(
8204                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
8205                                userId),
8206                        instantAppPkgName);
8207            }
8208            return Collections.emptyList();
8209        }
8210    }
8211
8212    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
8213            String instantAppPkgName) {
8214        // TODO: When adding on-demand split support for non-instant apps, remove this check
8215        // and always apply post filtering
8216        if (instantAppPkgName == null) {
8217            return resolveInfos;
8218        }
8219        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8220            final ResolveInfo info = resolveInfos.get(i);
8221            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
8222            // allow services that are defined in the provided package
8223            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
8224                if (info.serviceInfo.splitName != null
8225                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
8226                                info.serviceInfo.splitName)) {
8227                    // requested service is defined in a split that hasn't been installed yet.
8228                    // add the installer to the resolve list
8229                    if (DEBUG_EPHEMERAL) {
8230                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8231                    }
8232                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8233                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8234                            info.serviceInfo.packageName, info.serviceInfo.splitName,
8235                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
8236                    // make sure this resolver is the default
8237                    installerInfo.isDefault = true;
8238                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8239                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8240                    // add a non-generic filter
8241                    installerInfo.filter = new IntentFilter();
8242                    // load resources from the correct package
8243                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8244                    resolveInfos.set(i, installerInfo);
8245                }
8246                continue;
8247            }
8248            // allow services that have been explicitly exposed to ephemeral apps
8249            if (!isEphemeralApp
8250                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8251                continue;
8252            }
8253            resolveInfos.remove(i);
8254        }
8255        return resolveInfos;
8256    }
8257
8258    @Override
8259    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
8260            String resolvedType, int flags, int userId) {
8261        return new ParceledListSlice<>(
8262                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
8263    }
8264
8265    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
8266            Intent intent, String resolvedType, int flags, int userId) {
8267        if (!sUserManager.exists(userId)) return Collections.emptyList();
8268        final int callingUid = Binder.getCallingUid();
8269        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8270        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8271                false /*includeInstantApps*/);
8272        ComponentName comp = intent.getComponent();
8273        if (comp == null) {
8274            if (intent.getSelector() != null) {
8275                intent = intent.getSelector();
8276                comp = intent.getComponent();
8277            }
8278        }
8279        if (comp != null) {
8280            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8281            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8282            if (pi != null) {
8283                // When specifying an explicit component, we prevent the provider from being
8284                // used when either 1) the provider is in an instant application and the
8285                // caller is not the same instant application or 2) the calling package is an
8286                // instant application and the provider is not visible to instant applications.
8287                final boolean matchInstantApp =
8288                        (flags & PackageManager.MATCH_INSTANT) != 0;
8289                final boolean matchVisibleToInstantAppOnly =
8290                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8291                final boolean isCallerInstantApp =
8292                        instantAppPkgName != null;
8293                final boolean isTargetSameInstantApp =
8294                        comp.getPackageName().equals(instantAppPkgName);
8295                final boolean isTargetInstantApp =
8296                        (pi.applicationInfo.privateFlags
8297                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8298                final boolean isTargetHiddenFromInstantApp =
8299                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8300                final boolean blockResolution =
8301                        !isTargetSameInstantApp
8302                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8303                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8304                                        && isTargetHiddenFromInstantApp));
8305                if (!blockResolution) {
8306                    final ResolveInfo ri = new ResolveInfo();
8307                    ri.providerInfo = pi;
8308                    list.add(ri);
8309                }
8310            }
8311            return list;
8312        }
8313
8314        // reader
8315        synchronized (mPackages) {
8316            String pkgName = intent.getPackage();
8317            if (pkgName == null) {
8318                return applyPostContentProviderResolutionFilter(
8319                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8320                        instantAppPkgName);
8321            }
8322            final PackageParser.Package pkg = mPackages.get(pkgName);
8323            if (pkg != null) {
8324                return applyPostContentProviderResolutionFilter(
8325                        mProviders.queryIntentForPackage(
8326                        intent, resolvedType, flags, pkg.providers, userId),
8327                        instantAppPkgName);
8328            }
8329            return Collections.emptyList();
8330        }
8331    }
8332
8333    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8334            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8335        // TODO: When adding on-demand split support for non-instant applications, remove
8336        // this check and always apply post filtering
8337        if (instantAppPkgName == null) {
8338            return resolveInfos;
8339        }
8340        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8341            final ResolveInfo info = resolveInfos.get(i);
8342            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8343            // allow providers that are defined in the provided package
8344            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8345                if (info.providerInfo.splitName != null
8346                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8347                                info.providerInfo.splitName)) {
8348                    // requested provider is defined in a split that hasn't been installed yet.
8349                    // add the installer to the resolve list
8350                    if (DEBUG_EPHEMERAL) {
8351                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8352                    }
8353                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8354                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8355                            info.providerInfo.packageName, info.providerInfo.splitName,
8356                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
8357                    // make sure this resolver is the default
8358                    installerInfo.isDefault = true;
8359                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8360                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8361                    // add a non-generic filter
8362                    installerInfo.filter = new IntentFilter();
8363                    // load resources from the correct package
8364                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8365                    resolveInfos.set(i, installerInfo);
8366                }
8367                continue;
8368            }
8369            // allow providers that have been explicitly exposed to instant applications
8370            if (!isEphemeralApp
8371                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8372                continue;
8373            }
8374            resolveInfos.remove(i);
8375        }
8376        return resolveInfos;
8377    }
8378
8379    @Override
8380    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8381        final int callingUid = Binder.getCallingUid();
8382        if (getInstantAppPackageName(callingUid) != null) {
8383            return ParceledListSlice.emptyList();
8384        }
8385        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8386        flags = updateFlagsForPackage(flags, userId, null);
8387        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8388        enforceCrossUserPermission(callingUid, userId,
8389                true /* requireFullPermission */, false /* checkShell */,
8390                "get installed packages");
8391
8392        // writer
8393        synchronized (mPackages) {
8394            ArrayList<PackageInfo> list;
8395            if (listUninstalled) {
8396                list = new ArrayList<>(mSettings.mPackages.size());
8397                for (PackageSetting ps : mSettings.mPackages.values()) {
8398                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8399                        continue;
8400                    }
8401                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8402                        return null;
8403                    }
8404                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8405                    if (pi != null) {
8406                        list.add(pi);
8407                    }
8408                }
8409            } else {
8410                list = new ArrayList<>(mPackages.size());
8411                for (PackageParser.Package p : mPackages.values()) {
8412                    final PackageSetting ps = (PackageSetting) p.mExtras;
8413                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8414                        continue;
8415                    }
8416                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8417                        return null;
8418                    }
8419                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8420                            p.mExtras, flags, userId);
8421                    if (pi != null) {
8422                        list.add(pi);
8423                    }
8424                }
8425            }
8426
8427            return new ParceledListSlice<>(list);
8428        }
8429    }
8430
8431    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8432            String[] permissions, boolean[] tmp, int flags, int userId) {
8433        int numMatch = 0;
8434        final PermissionsState permissionsState = ps.getPermissionsState();
8435        for (int i=0; i<permissions.length; i++) {
8436            final String permission = permissions[i];
8437            if (permissionsState.hasPermission(permission, userId)) {
8438                tmp[i] = true;
8439                numMatch++;
8440            } else {
8441                tmp[i] = false;
8442            }
8443        }
8444        if (numMatch == 0) {
8445            return;
8446        }
8447        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8448
8449        // The above might return null in cases of uninstalled apps or install-state
8450        // skew across users/profiles.
8451        if (pi != null) {
8452            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8453                if (numMatch == permissions.length) {
8454                    pi.requestedPermissions = permissions;
8455                } else {
8456                    pi.requestedPermissions = new String[numMatch];
8457                    numMatch = 0;
8458                    for (int i=0; i<permissions.length; i++) {
8459                        if (tmp[i]) {
8460                            pi.requestedPermissions[numMatch] = permissions[i];
8461                            numMatch++;
8462                        }
8463                    }
8464                }
8465            }
8466            list.add(pi);
8467        }
8468    }
8469
8470    @Override
8471    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8472            String[] permissions, int flags, int userId) {
8473        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8474        flags = updateFlagsForPackage(flags, userId, permissions);
8475        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8476                true /* requireFullPermission */, false /* checkShell */,
8477                "get packages holding permissions");
8478        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8479
8480        // writer
8481        synchronized (mPackages) {
8482            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8483            boolean[] tmpBools = new boolean[permissions.length];
8484            if (listUninstalled) {
8485                for (PackageSetting ps : mSettings.mPackages.values()) {
8486                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8487                            userId);
8488                }
8489            } else {
8490                for (PackageParser.Package pkg : mPackages.values()) {
8491                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8492                    if (ps != null) {
8493                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8494                                userId);
8495                    }
8496                }
8497            }
8498
8499            return new ParceledListSlice<PackageInfo>(list);
8500        }
8501    }
8502
8503    @Override
8504    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8505        final int callingUid = Binder.getCallingUid();
8506        if (getInstantAppPackageName(callingUid) != null) {
8507            return ParceledListSlice.emptyList();
8508        }
8509        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8510        flags = updateFlagsForApplication(flags, userId, null);
8511        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8512
8513        // writer
8514        synchronized (mPackages) {
8515            ArrayList<ApplicationInfo> list;
8516            if (listUninstalled) {
8517                list = new ArrayList<>(mSettings.mPackages.size());
8518                for (PackageSetting ps : mSettings.mPackages.values()) {
8519                    ApplicationInfo ai;
8520                    int effectiveFlags = flags;
8521                    if (ps.isSystem()) {
8522                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8523                    }
8524                    if (ps.pkg != null) {
8525                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8526                            continue;
8527                        }
8528                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8529                            return null;
8530                        }
8531                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8532                                ps.readUserState(userId), userId);
8533                        if (ai != null) {
8534                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8535                        }
8536                    } else {
8537                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8538                        // and already converts to externally visible package name
8539                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8540                                callingUid, effectiveFlags, userId);
8541                    }
8542                    if (ai != null) {
8543                        list.add(ai);
8544                    }
8545                }
8546            } else {
8547                list = new ArrayList<>(mPackages.size());
8548                for (PackageParser.Package p : mPackages.values()) {
8549                    if (p.mExtras != null) {
8550                        PackageSetting ps = (PackageSetting) p.mExtras;
8551                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8552                            continue;
8553                        }
8554                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8555                            return null;
8556                        }
8557                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8558                                ps.readUserState(userId), userId);
8559                        if (ai != null) {
8560                            ai.packageName = resolveExternalPackageNameLPr(p);
8561                            list.add(ai);
8562                        }
8563                    }
8564                }
8565            }
8566
8567            return new ParceledListSlice<>(list);
8568        }
8569    }
8570
8571    @Override
8572    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8573        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8574            return null;
8575        }
8576        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8577            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8578                    "getEphemeralApplications");
8579        }
8580        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8581                true /* requireFullPermission */, false /* checkShell */,
8582                "getEphemeralApplications");
8583        synchronized (mPackages) {
8584            List<InstantAppInfo> instantApps = mInstantAppRegistry
8585                    .getInstantAppsLPr(userId);
8586            if (instantApps != null) {
8587                return new ParceledListSlice<>(instantApps);
8588            }
8589        }
8590        return null;
8591    }
8592
8593    @Override
8594    public boolean isInstantApp(String packageName, int userId) {
8595        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8596                true /* requireFullPermission */, false /* checkShell */,
8597                "isInstantApp");
8598        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8599            return false;
8600        }
8601
8602        synchronized (mPackages) {
8603            int callingUid = Binder.getCallingUid();
8604            if (Process.isIsolated(callingUid)) {
8605                callingUid = mIsolatedOwners.get(callingUid);
8606            }
8607            final PackageSetting ps = mSettings.mPackages.get(packageName);
8608            PackageParser.Package pkg = mPackages.get(packageName);
8609            final boolean returnAllowed =
8610                    ps != null
8611                    && (isCallerSameApp(packageName, callingUid)
8612                            || canViewInstantApps(callingUid, userId)
8613                            || mInstantAppRegistry.isInstantAccessGranted(
8614                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8615            if (returnAllowed) {
8616                return ps.getInstantApp(userId);
8617            }
8618        }
8619        return false;
8620    }
8621
8622    @Override
8623    public byte[] getInstantAppCookie(String packageName, int userId) {
8624        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8625            return null;
8626        }
8627
8628        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8629                true /* requireFullPermission */, false /* checkShell */,
8630                "getInstantAppCookie");
8631        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8632            return null;
8633        }
8634        synchronized (mPackages) {
8635            return mInstantAppRegistry.getInstantAppCookieLPw(
8636                    packageName, userId);
8637        }
8638    }
8639
8640    @Override
8641    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8642        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8643            return true;
8644        }
8645
8646        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8647                true /* requireFullPermission */, true /* checkShell */,
8648                "setInstantAppCookie");
8649        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8650            return false;
8651        }
8652        synchronized (mPackages) {
8653            return mInstantAppRegistry.setInstantAppCookieLPw(
8654                    packageName, cookie, userId);
8655        }
8656    }
8657
8658    @Override
8659    public Bitmap getInstantAppIcon(String packageName, int userId) {
8660        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8661            return null;
8662        }
8663
8664        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8665            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8666                    "getInstantAppIcon");
8667        }
8668        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8669                true /* requireFullPermission */, false /* checkShell */,
8670                "getInstantAppIcon");
8671
8672        synchronized (mPackages) {
8673            return mInstantAppRegistry.getInstantAppIconLPw(
8674                    packageName, userId);
8675        }
8676    }
8677
8678    private boolean isCallerSameApp(String packageName, int uid) {
8679        PackageParser.Package pkg = mPackages.get(packageName);
8680        return pkg != null
8681                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8682    }
8683
8684    @Override
8685    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8686        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8687            return ParceledListSlice.emptyList();
8688        }
8689        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8690    }
8691
8692    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8693        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8694
8695        // reader
8696        synchronized (mPackages) {
8697            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8698            final int userId = UserHandle.getCallingUserId();
8699            while (i.hasNext()) {
8700                final PackageParser.Package p = i.next();
8701                if (p.applicationInfo == null) continue;
8702
8703                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8704                        && !p.applicationInfo.isDirectBootAware();
8705                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8706                        && p.applicationInfo.isDirectBootAware();
8707
8708                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8709                        && (!mSafeMode || isSystemApp(p))
8710                        && (matchesUnaware || matchesAware)) {
8711                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8712                    if (ps != null) {
8713                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8714                                ps.readUserState(userId), userId);
8715                        if (ai != null) {
8716                            finalList.add(ai);
8717                        }
8718                    }
8719                }
8720            }
8721        }
8722
8723        return finalList;
8724    }
8725
8726    @Override
8727    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8728        if (!sUserManager.exists(userId)) return null;
8729        flags = updateFlagsForComponent(flags, userId, name);
8730        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8731        // reader
8732        synchronized (mPackages) {
8733            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8734            PackageSetting ps = provider != null
8735                    ? mSettings.mPackages.get(provider.owner.packageName)
8736                    : null;
8737            if (ps != null) {
8738                final boolean isInstantApp = ps.getInstantApp(userId);
8739                // normal application; filter out instant application provider
8740                if (instantAppPkgName == null && isInstantApp) {
8741                    return null;
8742                }
8743                // instant application; filter out other instant applications
8744                if (instantAppPkgName != null
8745                        && isInstantApp
8746                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8747                    return null;
8748                }
8749                // instant application; filter out non-exposed provider
8750                if (instantAppPkgName != null
8751                        && !isInstantApp
8752                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8753                    return null;
8754                }
8755                // provider not enabled
8756                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8757                    return null;
8758                }
8759                return PackageParser.generateProviderInfo(
8760                        provider, flags, ps.readUserState(userId), userId);
8761            }
8762            return null;
8763        }
8764    }
8765
8766    /**
8767     * @deprecated
8768     */
8769    @Deprecated
8770    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8771        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8772            return;
8773        }
8774        // reader
8775        synchronized (mPackages) {
8776            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8777                    .entrySet().iterator();
8778            final int userId = UserHandle.getCallingUserId();
8779            while (i.hasNext()) {
8780                Map.Entry<String, PackageParser.Provider> entry = i.next();
8781                PackageParser.Provider p = entry.getValue();
8782                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8783
8784                if (ps != null && p.syncable
8785                        && (!mSafeMode || (p.info.applicationInfo.flags
8786                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8787                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8788                            ps.readUserState(userId), userId);
8789                    if (info != null) {
8790                        outNames.add(entry.getKey());
8791                        outInfo.add(info);
8792                    }
8793                }
8794            }
8795        }
8796    }
8797
8798    @Override
8799    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8800            int uid, int flags, String metaDataKey) {
8801        final int callingUid = Binder.getCallingUid();
8802        final int userId = processName != null ? UserHandle.getUserId(uid)
8803                : UserHandle.getCallingUserId();
8804        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8805        flags = updateFlagsForComponent(flags, userId, processName);
8806        ArrayList<ProviderInfo> finalList = null;
8807        // reader
8808        synchronized (mPackages) {
8809            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8810            while (i.hasNext()) {
8811                final PackageParser.Provider p = i.next();
8812                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8813                if (ps != null && p.info.authority != null
8814                        && (processName == null
8815                                || (p.info.processName.equals(processName)
8816                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8817                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8818
8819                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8820                    // parameter.
8821                    if (metaDataKey != null
8822                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8823                        continue;
8824                    }
8825                    final ComponentName component =
8826                            new ComponentName(p.info.packageName, p.info.name);
8827                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8828                        continue;
8829                    }
8830                    if (finalList == null) {
8831                        finalList = new ArrayList<ProviderInfo>(3);
8832                    }
8833                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8834                            ps.readUserState(userId), userId);
8835                    if (info != null) {
8836                        finalList.add(info);
8837                    }
8838                }
8839            }
8840        }
8841
8842        if (finalList != null) {
8843            Collections.sort(finalList, mProviderInitOrderSorter);
8844            return new ParceledListSlice<ProviderInfo>(finalList);
8845        }
8846
8847        return ParceledListSlice.emptyList();
8848    }
8849
8850    @Override
8851    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8852        // reader
8853        synchronized (mPackages) {
8854            final int callingUid = Binder.getCallingUid();
8855            final int callingUserId = UserHandle.getUserId(callingUid);
8856            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8857            if (ps == null) return null;
8858            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8859                return null;
8860            }
8861            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8862            return PackageParser.generateInstrumentationInfo(i, flags);
8863        }
8864    }
8865
8866    @Override
8867    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8868            String targetPackage, int flags) {
8869        final int callingUid = Binder.getCallingUid();
8870        final int callingUserId = UserHandle.getUserId(callingUid);
8871        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8872        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8873            return ParceledListSlice.emptyList();
8874        }
8875        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8876    }
8877
8878    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8879            int flags) {
8880        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8881
8882        // reader
8883        synchronized (mPackages) {
8884            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8885            while (i.hasNext()) {
8886                final PackageParser.Instrumentation p = i.next();
8887                if (targetPackage == null
8888                        || targetPackage.equals(p.info.targetPackage)) {
8889                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8890                            flags);
8891                    if (ii != null) {
8892                        finalList.add(ii);
8893                    }
8894                }
8895            }
8896        }
8897
8898        return finalList;
8899    }
8900
8901    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8902        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8903        try {
8904            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8905        } finally {
8906            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8907        }
8908    }
8909
8910    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8911        final File[] files = dir.listFiles();
8912        if (ArrayUtils.isEmpty(files)) {
8913            Log.d(TAG, "No files in app dir " + dir);
8914            return;
8915        }
8916
8917        if (DEBUG_PACKAGE_SCANNING) {
8918            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8919                    + " flags=0x" + Integer.toHexString(parseFlags));
8920        }
8921        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8922                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8923                mParallelPackageParserCallback);
8924
8925        // Submit files for parsing in parallel
8926        int fileCount = 0;
8927        for (File file : files) {
8928            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8929                    && !PackageInstallerService.isStageName(file.getName());
8930            if (!isPackage) {
8931                // Ignore entries which are not packages
8932                continue;
8933            }
8934            parallelPackageParser.submit(file, parseFlags);
8935            fileCount++;
8936        }
8937
8938        // Process results one by one
8939        for (; fileCount > 0; fileCount--) {
8940            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8941            Throwable throwable = parseResult.throwable;
8942            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8943
8944            if (throwable == null) {
8945                // Static shared libraries have synthetic package names
8946                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8947                    renameStaticSharedLibraryPackage(parseResult.pkg);
8948                }
8949                try {
8950                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8951                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8952                                currentTime, null);
8953                    }
8954                } catch (PackageManagerException e) {
8955                    errorCode = e.error;
8956                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8957                }
8958            } else if (throwable instanceof PackageParser.PackageParserException) {
8959                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8960                        throwable;
8961                errorCode = e.error;
8962                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8963            } else {
8964                throw new IllegalStateException("Unexpected exception occurred while parsing "
8965                        + parseResult.scanFile, throwable);
8966            }
8967
8968            // Delete invalid userdata apps
8969            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8970                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8971                logCriticalInfo(Log.WARN,
8972                        "Deleting invalid package at " + parseResult.scanFile);
8973                removeCodePathLI(parseResult.scanFile);
8974            }
8975        }
8976        parallelPackageParser.close();
8977    }
8978
8979    private static File getSettingsProblemFile() {
8980        File dataDir = Environment.getDataDirectory();
8981        File systemDir = new File(dataDir, "system");
8982        File fname = new File(systemDir, "uiderrors.txt");
8983        return fname;
8984    }
8985
8986    static void reportSettingsProblem(int priority, String msg) {
8987        logCriticalInfo(priority, msg);
8988    }
8989
8990    public static void logCriticalInfo(int priority, String msg) {
8991        Slog.println(priority, TAG, msg);
8992        EventLogTags.writePmCriticalInfo(msg);
8993        try {
8994            File fname = getSettingsProblemFile();
8995            FileOutputStream out = new FileOutputStream(fname, true);
8996            PrintWriter pw = new FastPrintWriter(out);
8997            SimpleDateFormat formatter = new SimpleDateFormat();
8998            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8999            pw.println(dateString + ": " + msg);
9000            pw.close();
9001            FileUtils.setPermissions(
9002                    fname.toString(),
9003                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
9004                    -1, -1);
9005        } catch (java.io.IOException e) {
9006        }
9007    }
9008
9009    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
9010        if (srcFile.isDirectory()) {
9011            final File baseFile = new File(pkg.baseCodePath);
9012            long maxModifiedTime = baseFile.lastModified();
9013            if (pkg.splitCodePaths != null) {
9014                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
9015                    final File splitFile = new File(pkg.splitCodePaths[i]);
9016                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
9017                }
9018            }
9019            return maxModifiedTime;
9020        }
9021        return srcFile.lastModified();
9022    }
9023
9024    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
9025            final int policyFlags) throws PackageManagerException {
9026        // When upgrading from pre-N MR1, verify the package time stamp using the package
9027        // directory and not the APK file.
9028        final long lastModifiedTime = mIsPreNMR1Upgrade
9029                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
9030        if (ps != null
9031                && ps.codePath.equals(srcFile)
9032                && ps.timeStamp == lastModifiedTime
9033                && !isCompatSignatureUpdateNeeded(pkg)
9034                && !isRecoverSignatureUpdateNeeded(pkg)) {
9035            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
9036            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9037            ArraySet<PublicKey> signingKs;
9038            synchronized (mPackages) {
9039                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
9040            }
9041            if (ps.signatures.mSignatures != null
9042                    && ps.signatures.mSignatures.length != 0
9043                    && signingKs != null) {
9044                // Optimization: reuse the existing cached certificates
9045                // if the package appears to be unchanged.
9046                pkg.mSignatures = ps.signatures.mSignatures;
9047                pkg.mSigningKeys = signingKs;
9048                return;
9049            }
9050
9051            Slog.w(TAG, "PackageSetting for " + ps.name
9052                    + " is missing signatures.  Collecting certs again to recover them.");
9053        } else {
9054            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
9055        }
9056
9057        try {
9058            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
9059            PackageParser.collectCertificates(pkg, policyFlags);
9060        } catch (PackageParserException e) {
9061            throw PackageManagerException.from(e);
9062        } finally {
9063            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9064        }
9065    }
9066
9067    /**
9068     *  Traces a package scan.
9069     *  @see #scanPackageLI(File, int, int, long, UserHandle)
9070     */
9071    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
9072            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
9073        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
9074        try {
9075            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
9076        } finally {
9077            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9078        }
9079    }
9080
9081    /**
9082     *  Scans a package and returns the newly parsed package.
9083     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
9084     */
9085    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
9086            long currentTime, UserHandle user) throws PackageManagerException {
9087        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
9088        PackageParser pp = new PackageParser();
9089        pp.setSeparateProcesses(mSeparateProcesses);
9090        pp.setOnlyCoreApps(mOnlyCore);
9091        pp.setDisplayMetrics(mMetrics);
9092        pp.setCallback(mPackageParserCallback);
9093
9094        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
9095            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
9096        }
9097
9098        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
9099        final PackageParser.Package pkg;
9100        try {
9101            pkg = pp.parsePackage(scanFile, parseFlags);
9102        } catch (PackageParserException e) {
9103            throw PackageManagerException.from(e);
9104        } finally {
9105            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9106        }
9107
9108        // Static shared libraries have synthetic package names
9109        if (pkg.applicationInfo.isStaticSharedLibrary()) {
9110            renameStaticSharedLibraryPackage(pkg);
9111        }
9112
9113        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
9114    }
9115
9116    /**
9117     *  Scans a package and returns the newly parsed package.
9118     *  @throws PackageManagerException on a parse error.
9119     */
9120    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
9121            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9122            throws PackageManagerException {
9123        // If the package has children and this is the first dive in the function
9124        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
9125        // packages (parent and children) would be successfully scanned before the
9126        // actual scan since scanning mutates internal state and we want to atomically
9127        // install the package and its children.
9128        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9129            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9130                scanFlags |= SCAN_CHECK_ONLY;
9131            }
9132        } else {
9133            scanFlags &= ~SCAN_CHECK_ONLY;
9134        }
9135
9136        // Scan the parent
9137        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
9138                scanFlags, currentTime, user);
9139
9140        // Scan the children
9141        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9142        for (int i = 0; i < childCount; i++) {
9143            PackageParser.Package childPackage = pkg.childPackages.get(i);
9144            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
9145                    currentTime, user);
9146        }
9147
9148
9149        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9150            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
9151        }
9152
9153        return scannedPkg;
9154    }
9155
9156    /**
9157     *  Scans a package and returns the newly parsed package.
9158     *  @throws PackageManagerException on a parse error.
9159     */
9160    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
9161            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9162            throws PackageManagerException {
9163        PackageSetting ps = null;
9164        PackageSetting updatedPkg;
9165        // reader
9166        synchronized (mPackages) {
9167            // Look to see if we already know about this package.
9168            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
9169            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
9170                // This package has been renamed to its original name.  Let's
9171                // use that.
9172                ps = mSettings.getPackageLPr(oldName);
9173            }
9174            // If there was no original package, see one for the real package name.
9175            if (ps == null) {
9176                ps = mSettings.getPackageLPr(pkg.packageName);
9177            }
9178            // Check to see if this package could be hiding/updating a system
9179            // package.  Must look for it either under the original or real
9180            // package name depending on our state.
9181            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
9182            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
9183
9184            // If this is a package we don't know about on the system partition, we
9185            // may need to remove disabled child packages on the system partition
9186            // or may need to not add child packages if the parent apk is updated
9187            // on the data partition and no longer defines this child package.
9188            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
9189                // If this is a parent package for an updated system app and this system
9190                // app got an OTA update which no longer defines some of the child packages
9191                // we have to prune them from the disabled system packages.
9192                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9193                if (disabledPs != null) {
9194                    final int scannedChildCount = (pkg.childPackages != null)
9195                            ? pkg.childPackages.size() : 0;
9196                    final int disabledChildCount = disabledPs.childPackageNames != null
9197                            ? disabledPs.childPackageNames.size() : 0;
9198                    for (int i = 0; i < disabledChildCount; i++) {
9199                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
9200                        boolean disabledPackageAvailable = false;
9201                        for (int j = 0; j < scannedChildCount; j++) {
9202                            PackageParser.Package childPkg = pkg.childPackages.get(j);
9203                            if (childPkg.packageName.equals(disabledChildPackageName)) {
9204                                disabledPackageAvailable = true;
9205                                break;
9206                            }
9207                         }
9208                         if (!disabledPackageAvailable) {
9209                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
9210                         }
9211                    }
9212                }
9213            }
9214        }
9215
9216        final boolean isUpdatedPkg = updatedPkg != null;
9217        final boolean isUpdatedSystemPkg = isUpdatedPkg
9218                && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0;
9219        boolean isUpdatedPkgBetter = false;
9220        // First check if this is a system package that may involve an update
9221        if (isUpdatedSystemPkg) {
9222            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
9223            // it needs to drop FLAG_PRIVILEGED.
9224            if (locationIsPrivileged(scanFile)) {
9225                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9226            } else {
9227                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9228            }
9229
9230            if (ps != null && !ps.codePath.equals(scanFile)) {
9231                // The path has changed from what was last scanned...  check the
9232                // version of the new path against what we have stored to determine
9233                // what to do.
9234                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
9235                if (pkg.mVersionCode <= ps.versionCode) {
9236                    // The system package has been updated and the code path does not match
9237                    // Ignore entry. Skip it.
9238                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
9239                            + " ignored: updated version " + ps.versionCode
9240                            + " better than this " + pkg.mVersionCode);
9241                    if (!updatedPkg.codePath.equals(scanFile)) {
9242                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
9243                                + ps.name + " changing from " + updatedPkg.codePathString
9244                                + " to " + scanFile);
9245                        updatedPkg.codePath = scanFile;
9246                        updatedPkg.codePathString = scanFile.toString();
9247                        updatedPkg.resourcePath = scanFile;
9248                        updatedPkg.resourcePathString = scanFile.toString();
9249                    }
9250                    updatedPkg.pkg = pkg;
9251                    updatedPkg.versionCode = pkg.mVersionCode;
9252
9253                    // Update the disabled system child packages to point to the package too.
9254                    final int childCount = updatedPkg.childPackageNames != null
9255                            ? updatedPkg.childPackageNames.size() : 0;
9256                    for (int i = 0; i < childCount; i++) {
9257                        String childPackageName = updatedPkg.childPackageNames.get(i);
9258                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
9259                                childPackageName);
9260                        if (updatedChildPkg != null) {
9261                            updatedChildPkg.pkg = pkg;
9262                            updatedChildPkg.versionCode = pkg.mVersionCode;
9263                        }
9264                    }
9265                } else {
9266                    // The current app on the system partition is better than
9267                    // what we have updated to on the data partition; switch
9268                    // back to the system partition version.
9269                    // At this point, its safely assumed that package installation for
9270                    // apps in system partition will go through. If not there won't be a working
9271                    // version of the app
9272                    // writer
9273                    synchronized (mPackages) {
9274                        // Just remove the loaded entries from package lists.
9275                        mPackages.remove(ps.name);
9276                    }
9277
9278                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9279                            + " reverting from " + ps.codePathString
9280                            + ": new version " + pkg.mVersionCode
9281                            + " better than installed " + ps.versionCode);
9282
9283                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9284                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9285                    synchronized (mInstallLock) {
9286                        args.cleanUpResourcesLI();
9287                    }
9288                    synchronized (mPackages) {
9289                        mSettings.enableSystemPackageLPw(ps.name);
9290                    }
9291                    isUpdatedPkgBetter = true;
9292                }
9293            }
9294        }
9295
9296        String resourcePath = null;
9297        String baseResourcePath = null;
9298        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !isUpdatedPkgBetter) {
9299            if (ps != null && ps.resourcePathString != null) {
9300                resourcePath = ps.resourcePathString;
9301                baseResourcePath = ps.resourcePathString;
9302            } else {
9303                // Should not happen at all. Just log an error.
9304                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9305            }
9306        } else {
9307            resourcePath = pkg.codePath;
9308            baseResourcePath = pkg.baseCodePath;
9309        }
9310
9311        // Set application objects path explicitly.
9312        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9313        pkg.setApplicationInfoCodePath(pkg.codePath);
9314        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9315        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9316        pkg.setApplicationInfoResourcePath(resourcePath);
9317        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9318        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9319
9320        // throw an exception if we have an update to a system application, but, it's not more
9321        // recent than the package we've already scanned
9322        if (isUpdatedSystemPkg && !isUpdatedPkgBetter) {
9323            throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9324                    + scanFile + " ignored: updated version " + ps.versionCode
9325                    + " better than this " + pkg.mVersionCode);
9326        }
9327
9328        if (isUpdatedPkg) {
9329            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9330            // initially
9331            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9332
9333            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9334            // flag set initially
9335            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9336                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9337            }
9338        }
9339
9340        // Verify certificates against what was last scanned
9341        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9342
9343        /*
9344         * A new system app appeared, but we already had a non-system one of the
9345         * same name installed earlier.
9346         */
9347        boolean shouldHideSystemApp = false;
9348        if (!isUpdatedPkg && ps != null
9349                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9350            /*
9351             * Check to make sure the signatures match first. If they don't,
9352             * wipe the installed application and its data.
9353             */
9354            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9355                    != PackageManager.SIGNATURE_MATCH) {
9356                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9357                        + " signatures don't match existing userdata copy; removing");
9358                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9359                        "scanPackageInternalLI")) {
9360                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9361                }
9362                ps = null;
9363            } else {
9364                /*
9365                 * If the newly-added system app is an older version than the
9366                 * already installed version, hide it. It will be scanned later
9367                 * and re-added like an update.
9368                 */
9369                if (pkg.mVersionCode <= ps.versionCode) {
9370                    shouldHideSystemApp = true;
9371                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9372                            + " but new version " + pkg.mVersionCode + " better than installed "
9373                            + ps.versionCode + "; hiding system");
9374                } else {
9375                    /*
9376                     * The newly found system app is a newer version that the
9377                     * one previously installed. Simply remove the
9378                     * already-installed application and replace it with our own
9379                     * while keeping the application data.
9380                     */
9381                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9382                            + " reverting from " + ps.codePathString + ": new version "
9383                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9384                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9385                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9386                    synchronized (mInstallLock) {
9387                        args.cleanUpResourcesLI();
9388                    }
9389                }
9390            }
9391        }
9392
9393        // The apk is forward locked (not public) if its code and resources
9394        // are kept in different files. (except for app in either system or
9395        // vendor path).
9396        // TODO grab this value from PackageSettings
9397        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9398            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9399                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9400            }
9401        }
9402
9403        final int userId = ((user == null) ? 0 : user.getIdentifier());
9404        if (ps != null && ps.getInstantApp(userId)) {
9405            scanFlags |= SCAN_AS_INSTANT_APP;
9406        }
9407
9408        // Note that we invoke the following method only if we are about to unpack an application
9409        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9410                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9411
9412        /*
9413         * If the system app should be overridden by a previously installed
9414         * data, hide the system app now and let the /data/app scan pick it up
9415         * again.
9416         */
9417        if (shouldHideSystemApp) {
9418            synchronized (mPackages) {
9419                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9420            }
9421        }
9422
9423        return scannedPkg;
9424    }
9425
9426    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9427        // Derive the new package synthetic package name
9428        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9429                + pkg.staticSharedLibVersion);
9430    }
9431
9432    private static String fixProcessName(String defProcessName,
9433            String processName) {
9434        if (processName == null) {
9435            return defProcessName;
9436        }
9437        return processName;
9438    }
9439
9440    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9441            throws PackageManagerException {
9442        if (pkgSetting.signatures.mSignatures != null) {
9443            // Already existing package. Make sure signatures match
9444            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9445                    == PackageManager.SIGNATURE_MATCH;
9446            if (!match) {
9447                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9448                        == PackageManager.SIGNATURE_MATCH;
9449            }
9450            if (!match) {
9451                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9452                        == PackageManager.SIGNATURE_MATCH;
9453            }
9454            if (!match) {
9455                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9456                        + pkg.packageName + " signatures do not match the "
9457                        + "previously installed version; ignoring!");
9458            }
9459        }
9460
9461        // Check for shared user signatures
9462        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9463            // Already existing package. Make sure signatures match
9464            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9465                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9466            if (!match) {
9467                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9468                        == PackageManager.SIGNATURE_MATCH;
9469            }
9470            if (!match) {
9471                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9472                        == PackageManager.SIGNATURE_MATCH;
9473            }
9474            if (!match) {
9475                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9476                        "Package " + pkg.packageName
9477                        + " has no signatures that match those in shared user "
9478                        + pkgSetting.sharedUser.name + "; ignoring!");
9479            }
9480        }
9481    }
9482
9483    /**
9484     * Enforces that only the system UID or root's UID can call a method exposed
9485     * via Binder.
9486     *
9487     * @param message used as message if SecurityException is thrown
9488     * @throws SecurityException if the caller is not system or root
9489     */
9490    private static final void enforceSystemOrRoot(String message) {
9491        final int uid = Binder.getCallingUid();
9492        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9493            throw new SecurityException(message);
9494        }
9495    }
9496
9497    @Override
9498    public void performFstrimIfNeeded() {
9499        enforceSystemOrRoot("Only the system can request fstrim");
9500
9501        // Before everything else, see whether we need to fstrim.
9502        try {
9503            IStorageManager sm = PackageHelper.getStorageManager();
9504            if (sm != null) {
9505                boolean doTrim = false;
9506                final long interval = android.provider.Settings.Global.getLong(
9507                        mContext.getContentResolver(),
9508                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9509                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9510                if (interval > 0) {
9511                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9512                    if (timeSinceLast > interval) {
9513                        doTrim = true;
9514                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9515                                + "; running immediately");
9516                    }
9517                }
9518                if (doTrim) {
9519                    final boolean dexOptDialogShown;
9520                    synchronized (mPackages) {
9521                        dexOptDialogShown = mDexOptDialogShown;
9522                    }
9523                    if (!isFirstBoot() && dexOptDialogShown) {
9524                        try {
9525                            ActivityManager.getService().showBootMessage(
9526                                    mContext.getResources().getString(
9527                                            R.string.android_upgrading_fstrim), true);
9528                        } catch (RemoteException e) {
9529                        }
9530                    }
9531                    sm.runMaintenance();
9532                }
9533            } else {
9534                Slog.e(TAG, "storageManager service unavailable!");
9535            }
9536        } catch (RemoteException e) {
9537            // Can't happen; StorageManagerService is local
9538        }
9539    }
9540
9541    @Override
9542    public void updatePackagesIfNeeded() {
9543        enforceSystemOrRoot("Only the system can request package update");
9544
9545        // We need to re-extract after an OTA.
9546        boolean causeUpgrade = isUpgrade();
9547
9548        // First boot or factory reset.
9549        // Note: we also handle devices that are upgrading to N right now as if it is their
9550        //       first boot, as they do not have profile data.
9551        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9552
9553        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9554        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9555
9556        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9557            return;
9558        }
9559
9560        List<PackageParser.Package> pkgs;
9561        synchronized (mPackages) {
9562            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9563        }
9564
9565        final long startTime = System.nanoTime();
9566        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9567                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9568                    false /* bootComplete */);
9569
9570        final int elapsedTimeSeconds =
9571                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9572
9573        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9574        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9575        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9576        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9577        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9578    }
9579
9580    /*
9581     * Return the prebuilt profile path given a package base code path.
9582     */
9583    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9584        return pkg.baseCodePath + ".prof";
9585    }
9586
9587    /**
9588     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9589     * containing statistics about the invocation. The array consists of three elements,
9590     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9591     * and {@code numberOfPackagesFailed}.
9592     */
9593    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9594            String compilerFilter, boolean bootComplete) {
9595
9596        int numberOfPackagesVisited = 0;
9597        int numberOfPackagesOptimized = 0;
9598        int numberOfPackagesSkipped = 0;
9599        int numberOfPackagesFailed = 0;
9600        final int numberOfPackagesToDexopt = pkgs.size();
9601
9602        for (PackageParser.Package pkg : pkgs) {
9603            numberOfPackagesVisited++;
9604
9605            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9606                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9607                // that are already compiled.
9608                File profileFile = new File(getPrebuildProfilePath(pkg));
9609                // Copy profile if it exists.
9610                if (profileFile.exists()) {
9611                    try {
9612                        // We could also do this lazily before calling dexopt in
9613                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9614                        // is that we don't have a good way to say "do this only once".
9615                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9616                                pkg.applicationInfo.uid, pkg.packageName)) {
9617                            Log.e(TAG, "Installer failed to copy system profile!");
9618                        }
9619                    } catch (Exception e) {
9620                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9621                                e);
9622                    }
9623                }
9624            }
9625
9626            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9627                if (DEBUG_DEXOPT) {
9628                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9629                }
9630                numberOfPackagesSkipped++;
9631                continue;
9632            }
9633
9634            if (DEBUG_DEXOPT) {
9635                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9636                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9637            }
9638
9639            if (showDialog) {
9640                try {
9641                    ActivityManager.getService().showBootMessage(
9642                            mContext.getResources().getString(R.string.android_upgrading_apk,
9643                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9644                } catch (RemoteException e) {
9645                }
9646                synchronized (mPackages) {
9647                    mDexOptDialogShown = true;
9648                }
9649            }
9650
9651            // If the OTA updates a system app which was previously preopted to a non-preopted state
9652            // the app might end up being verified at runtime. That's because by default the apps
9653            // are verify-profile but for preopted apps there's no profile.
9654            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9655            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9656            // filter (by default 'quicken').
9657            // Note that at this stage unused apps are already filtered.
9658            if (isSystemApp(pkg) &&
9659                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9660                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9661                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9662            }
9663
9664            // checkProfiles is false to avoid merging profiles during boot which
9665            // might interfere with background compilation (b/28612421).
9666            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9667            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9668            // trade-off worth doing to save boot time work.
9669            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9670            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9671                    pkg.packageName,
9672                    compilerFilter,
9673                    dexoptFlags));
9674
9675            if (pkg.isSystemApp()) {
9676                // Only dexopt shared secondary dex files belonging to system apps to not slow down
9677                // too much boot after an OTA.
9678                int secondaryDexoptFlags = dexoptFlags |
9679                        DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9680                        DexoptOptions.DEXOPT_ONLY_SHARED_DEX;
9681                mDexManager.dexoptSecondaryDex(new DexoptOptions(
9682                        pkg.packageName,
9683                        compilerFilter,
9684                        secondaryDexoptFlags));
9685            }
9686
9687            // TODO(shubhamajmera): Record secondary dexopt stats.
9688            switch (primaryDexOptStaus) {
9689                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9690                    numberOfPackagesOptimized++;
9691                    break;
9692                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9693                    numberOfPackagesSkipped++;
9694                    break;
9695                case PackageDexOptimizer.DEX_OPT_FAILED:
9696                    numberOfPackagesFailed++;
9697                    break;
9698                default:
9699                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9700                    break;
9701            }
9702        }
9703
9704        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9705                numberOfPackagesFailed };
9706    }
9707
9708    @Override
9709    public void notifyPackageUse(String packageName, int reason) {
9710        synchronized (mPackages) {
9711            final int callingUid = Binder.getCallingUid();
9712            final int callingUserId = UserHandle.getUserId(callingUid);
9713            if (getInstantAppPackageName(callingUid) != null) {
9714                if (!isCallerSameApp(packageName, callingUid)) {
9715                    return;
9716                }
9717            } else {
9718                if (isInstantApp(packageName, callingUserId)) {
9719                    return;
9720                }
9721            }
9722            final PackageParser.Package p = mPackages.get(packageName);
9723            if (p == null) {
9724                return;
9725            }
9726            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9727        }
9728    }
9729
9730    @Override
9731    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9732            List<String> classPaths, String loaderIsa) {
9733        int userId = UserHandle.getCallingUserId();
9734        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9735        if (ai == null) {
9736            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9737                + loadingPackageName + ", user=" + userId);
9738            return;
9739        }
9740        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9741    }
9742
9743    @Override
9744    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9745            IDexModuleRegisterCallback callback) {
9746        int userId = UserHandle.getCallingUserId();
9747        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9748        DexManager.RegisterDexModuleResult result;
9749        if (ai == null) {
9750            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9751                     " calling user. package=" + packageName + ", user=" + userId);
9752            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9753        } else {
9754            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9755        }
9756
9757        if (callback != null) {
9758            mHandler.post(() -> {
9759                try {
9760                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9761                } catch (RemoteException e) {
9762                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9763                }
9764            });
9765        }
9766    }
9767
9768    /**
9769     * Ask the package manager to perform a dex-opt with the given compiler filter.
9770     *
9771     * Note: exposed only for the shell command to allow moving packages explicitly to a
9772     *       definite state.
9773     */
9774    @Override
9775    public boolean performDexOptMode(String packageName,
9776            boolean checkProfiles, String targetCompilerFilter, boolean force,
9777            boolean bootComplete, String splitName) {
9778        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9779                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9780                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9781        return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter,
9782                splitName, flags));
9783    }
9784
9785    /**
9786     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9787     * secondary dex files belonging to the given package.
9788     *
9789     * Note: exposed only for the shell command to allow moving packages explicitly to a
9790     *       definite state.
9791     */
9792    @Override
9793    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9794            boolean force) {
9795        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9796                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9797                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9798                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9799        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9800    }
9801
9802    /*package*/ boolean performDexOpt(DexoptOptions options) {
9803        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9804            return false;
9805        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9806            return false;
9807        }
9808
9809        if (options.isDexoptOnlySecondaryDex()) {
9810            return mDexManager.dexoptSecondaryDex(options);
9811        } else {
9812            int dexoptStatus = performDexOptWithStatus(options);
9813            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9814        }
9815    }
9816
9817    /**
9818     * Perform dexopt on the given package and return one of following result:
9819     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9820     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9821     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9822     */
9823    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9824        return performDexOptTraced(options);
9825    }
9826
9827    private int performDexOptTraced(DexoptOptions options) {
9828        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9829        try {
9830            return performDexOptInternal(options);
9831        } finally {
9832            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9833        }
9834    }
9835
9836    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9837    // if the package can now be considered up to date for the given filter.
9838    private int performDexOptInternal(DexoptOptions options) {
9839        PackageParser.Package p;
9840        synchronized (mPackages) {
9841            p = mPackages.get(options.getPackageName());
9842            if (p == null) {
9843                // Package could not be found. Report failure.
9844                return PackageDexOptimizer.DEX_OPT_FAILED;
9845            }
9846            mPackageUsage.maybeWriteAsync(mPackages);
9847            mCompilerStats.maybeWriteAsync();
9848        }
9849        long callingId = Binder.clearCallingIdentity();
9850        try {
9851            synchronized (mInstallLock) {
9852                return performDexOptInternalWithDependenciesLI(p, options);
9853            }
9854        } finally {
9855            Binder.restoreCallingIdentity(callingId);
9856        }
9857    }
9858
9859    public ArraySet<String> getOptimizablePackages() {
9860        ArraySet<String> pkgs = new ArraySet<String>();
9861        synchronized (mPackages) {
9862            for (PackageParser.Package p : mPackages.values()) {
9863                if (PackageDexOptimizer.canOptimizePackage(p)) {
9864                    pkgs.add(p.packageName);
9865                }
9866            }
9867        }
9868        return pkgs;
9869    }
9870
9871    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9872            DexoptOptions options) {
9873        // Select the dex optimizer based on the force parameter.
9874        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9875        //       allocate an object here.
9876        PackageDexOptimizer pdo = options.isForce()
9877                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9878                : mPackageDexOptimizer;
9879
9880        // Dexopt all dependencies first. Note: we ignore the return value and march on
9881        // on errors.
9882        // Note that we are going to call performDexOpt on those libraries as many times as
9883        // they are referenced in packages. When we do a batch of performDexOpt (for example
9884        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9885        // and the first package that uses the library will dexopt it. The
9886        // others will see that the compiled code for the library is up to date.
9887        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9888        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9889        if (!deps.isEmpty()) {
9890            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9891                    options.getCompilerFilter(), options.getSplitName(),
9892                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9893            for (PackageParser.Package depPackage : deps) {
9894                // TODO: Analyze and investigate if we (should) profile libraries.
9895                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9896                        getOrCreateCompilerPackageStats(depPackage),
9897                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9898            }
9899        }
9900        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9901                getOrCreateCompilerPackageStats(p),
9902                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9903    }
9904
9905    /**
9906     * Reconcile the information we have about the secondary dex files belonging to
9907     * {@code packagName} and the actual dex files. For all dex files that were
9908     * deleted, update the internal records and delete the generated oat files.
9909     */
9910    @Override
9911    public void reconcileSecondaryDexFiles(String packageName) {
9912        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9913            return;
9914        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9915            return;
9916        }
9917        mDexManager.reconcileSecondaryDexFiles(packageName);
9918    }
9919
9920    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9921    // a reference there.
9922    /*package*/ DexManager getDexManager() {
9923        return mDexManager;
9924    }
9925
9926    /**
9927     * Execute the background dexopt job immediately.
9928     */
9929    @Override
9930    public boolean runBackgroundDexoptJob() {
9931        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9932            return false;
9933        }
9934        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9935    }
9936
9937    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9938        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9939                || p.usesStaticLibraries != null) {
9940            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9941            Set<String> collectedNames = new HashSet<>();
9942            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9943
9944            retValue.remove(p);
9945
9946            return retValue;
9947        } else {
9948            return Collections.emptyList();
9949        }
9950    }
9951
9952    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9953            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9954        if (!collectedNames.contains(p.packageName)) {
9955            collectedNames.add(p.packageName);
9956            collected.add(p);
9957
9958            if (p.usesLibraries != null) {
9959                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9960                        null, collected, collectedNames);
9961            }
9962            if (p.usesOptionalLibraries != null) {
9963                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9964                        null, collected, collectedNames);
9965            }
9966            if (p.usesStaticLibraries != null) {
9967                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9968                        p.usesStaticLibrariesVersions, collected, collectedNames);
9969            }
9970        }
9971    }
9972
9973    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9974            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9975        final int libNameCount = libs.size();
9976        for (int i = 0; i < libNameCount; i++) {
9977            String libName = libs.get(i);
9978            int version = (versions != null && versions.length == libNameCount)
9979                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9980            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9981            if (libPkg != null) {
9982                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9983            }
9984        }
9985    }
9986
9987    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9988        synchronized (mPackages) {
9989            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9990            if (libEntry != null) {
9991                return mPackages.get(libEntry.apk);
9992            }
9993            return null;
9994        }
9995    }
9996
9997    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9998        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9999        if (versionedLib == null) {
10000            return null;
10001        }
10002        return versionedLib.get(version);
10003    }
10004
10005    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
10006        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10007                pkg.staticSharedLibName);
10008        if (versionedLib == null) {
10009            return null;
10010        }
10011        int previousLibVersion = -1;
10012        final int versionCount = versionedLib.size();
10013        for (int i = 0; i < versionCount; i++) {
10014            final int libVersion = versionedLib.keyAt(i);
10015            if (libVersion < pkg.staticSharedLibVersion) {
10016                previousLibVersion = Math.max(previousLibVersion, libVersion);
10017            }
10018        }
10019        if (previousLibVersion >= 0) {
10020            return versionedLib.get(previousLibVersion);
10021        }
10022        return null;
10023    }
10024
10025    public void shutdown() {
10026        mPackageUsage.writeNow(mPackages);
10027        mCompilerStats.writeNow();
10028        mDexManager.writePackageDexUsageNow();
10029    }
10030
10031    @Override
10032    public void dumpProfiles(String packageName) {
10033        PackageParser.Package pkg;
10034        synchronized (mPackages) {
10035            pkg = mPackages.get(packageName);
10036            if (pkg == null) {
10037                throw new IllegalArgumentException("Unknown package: " + packageName);
10038            }
10039        }
10040        /* Only the shell, root, or the app user should be able to dump profiles. */
10041        int callingUid = Binder.getCallingUid();
10042        if (callingUid != Process.SHELL_UID &&
10043            callingUid != Process.ROOT_UID &&
10044            callingUid != pkg.applicationInfo.uid) {
10045            throw new SecurityException("dumpProfiles");
10046        }
10047
10048        synchronized (mInstallLock) {
10049            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
10050            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
10051            try {
10052                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
10053                String codePaths = TextUtils.join(";", allCodePaths);
10054                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
10055            } catch (InstallerException e) {
10056                Slog.w(TAG, "Failed to dump profiles", e);
10057            }
10058            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10059        }
10060    }
10061
10062    @Override
10063    public void forceDexOpt(String packageName) {
10064        enforceSystemOrRoot("forceDexOpt");
10065
10066        PackageParser.Package pkg;
10067        synchronized (mPackages) {
10068            pkg = mPackages.get(packageName);
10069            if (pkg == null) {
10070                throw new IllegalArgumentException("Unknown package: " + packageName);
10071            }
10072        }
10073
10074        synchronized (mInstallLock) {
10075            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
10076
10077            // Whoever is calling forceDexOpt wants a compiled package.
10078            // Don't use profiles since that may cause compilation to be skipped.
10079            final int res = performDexOptInternalWithDependenciesLI(
10080                    pkg,
10081                    new DexoptOptions(packageName,
10082                            getDefaultCompilerFilter(),
10083                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
10084
10085            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10086            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
10087                throw new IllegalStateException("Failed to dexopt: " + res);
10088            }
10089        }
10090    }
10091
10092    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
10093        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
10094            Slog.w(TAG, "Unable to update from " + oldPkg.name
10095                    + " to " + newPkg.packageName
10096                    + ": old package not in system partition");
10097            return false;
10098        } else if (mPackages.get(oldPkg.name) != null) {
10099            Slog.w(TAG, "Unable to update from " + oldPkg.name
10100                    + " to " + newPkg.packageName
10101                    + ": old package still exists");
10102            return false;
10103        }
10104        return true;
10105    }
10106
10107    void removeCodePathLI(File codePath) {
10108        if (codePath.isDirectory()) {
10109            try {
10110                mInstaller.rmPackageDir(codePath.getAbsolutePath());
10111            } catch (InstallerException e) {
10112                Slog.w(TAG, "Failed to remove code path", e);
10113            }
10114        } else {
10115            codePath.delete();
10116        }
10117    }
10118
10119    private int[] resolveUserIds(int userId) {
10120        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
10121    }
10122
10123    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10124        if (pkg == null) {
10125            Slog.wtf(TAG, "Package was null!", new Throwable());
10126            return;
10127        }
10128        clearAppDataLeafLIF(pkg, userId, flags);
10129        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10130        for (int i = 0; i < childCount; i++) {
10131            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10132        }
10133    }
10134
10135    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10136        final PackageSetting ps;
10137        synchronized (mPackages) {
10138            ps = mSettings.mPackages.get(pkg.packageName);
10139        }
10140        for (int realUserId : resolveUserIds(userId)) {
10141            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10142            try {
10143                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10144                        ceDataInode);
10145            } catch (InstallerException e) {
10146                Slog.w(TAG, String.valueOf(e));
10147            }
10148        }
10149    }
10150
10151    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10152        if (pkg == null) {
10153            Slog.wtf(TAG, "Package was null!", new Throwable());
10154            return;
10155        }
10156        destroyAppDataLeafLIF(pkg, userId, flags);
10157        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10158        for (int i = 0; i < childCount; i++) {
10159            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10160        }
10161    }
10162
10163    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10164        final PackageSetting ps;
10165        synchronized (mPackages) {
10166            ps = mSettings.mPackages.get(pkg.packageName);
10167        }
10168        for (int realUserId : resolveUserIds(userId)) {
10169            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10170            try {
10171                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10172                        ceDataInode);
10173            } catch (InstallerException e) {
10174                Slog.w(TAG, String.valueOf(e));
10175            }
10176            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
10177        }
10178    }
10179
10180    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
10181        if (pkg == null) {
10182            Slog.wtf(TAG, "Package was null!", new Throwable());
10183            return;
10184        }
10185        destroyAppProfilesLeafLIF(pkg);
10186        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10187        for (int i = 0; i < childCount; i++) {
10188            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
10189        }
10190    }
10191
10192    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
10193        try {
10194            mInstaller.destroyAppProfiles(pkg.packageName);
10195        } catch (InstallerException e) {
10196            Slog.w(TAG, String.valueOf(e));
10197        }
10198    }
10199
10200    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
10201        if (pkg == null) {
10202            Slog.wtf(TAG, "Package was null!", new Throwable());
10203            return;
10204        }
10205        clearAppProfilesLeafLIF(pkg);
10206        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10207        for (int i = 0; i < childCount; i++) {
10208            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
10209        }
10210    }
10211
10212    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
10213        try {
10214            mInstaller.clearAppProfiles(pkg.packageName);
10215        } catch (InstallerException e) {
10216            Slog.w(TAG, String.valueOf(e));
10217        }
10218    }
10219
10220    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
10221            long lastUpdateTime) {
10222        // Set parent install/update time
10223        PackageSetting ps = (PackageSetting) pkg.mExtras;
10224        if (ps != null) {
10225            ps.firstInstallTime = firstInstallTime;
10226            ps.lastUpdateTime = lastUpdateTime;
10227        }
10228        // Set children install/update time
10229        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10230        for (int i = 0; i < childCount; i++) {
10231            PackageParser.Package childPkg = pkg.childPackages.get(i);
10232            ps = (PackageSetting) childPkg.mExtras;
10233            if (ps != null) {
10234                ps.firstInstallTime = firstInstallTime;
10235                ps.lastUpdateTime = lastUpdateTime;
10236            }
10237        }
10238    }
10239
10240    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
10241            PackageParser.Package changingLib) {
10242        if (file.path != null) {
10243            usesLibraryFiles.add(file.path);
10244            return;
10245        }
10246        PackageParser.Package p = mPackages.get(file.apk);
10247        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
10248            // If we are doing this while in the middle of updating a library apk,
10249            // then we need to make sure to use that new apk for determining the
10250            // dependencies here.  (We haven't yet finished committing the new apk
10251            // to the package manager state.)
10252            if (p == null || p.packageName.equals(changingLib.packageName)) {
10253                p = changingLib;
10254            }
10255        }
10256        if (p != null) {
10257            usesLibraryFiles.addAll(p.getAllCodePaths());
10258            if (p.usesLibraryFiles != null) {
10259                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
10260            }
10261        }
10262    }
10263
10264    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
10265            PackageParser.Package changingLib) throws PackageManagerException {
10266        if (pkg == null) {
10267            return;
10268        }
10269        ArraySet<String> usesLibraryFiles = null;
10270        if (pkg.usesLibraries != null) {
10271            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
10272                    null, null, pkg.packageName, changingLib, true, null);
10273        }
10274        if (pkg.usesStaticLibraries != null) {
10275            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
10276                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
10277                    pkg.packageName, changingLib, true, usesLibraryFiles);
10278        }
10279        if (pkg.usesOptionalLibraries != null) {
10280            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
10281                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
10282        }
10283        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
10284            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10285        } else {
10286            pkg.usesLibraryFiles = null;
10287        }
10288    }
10289
10290    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10291            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
10292            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10293            boolean required, @Nullable ArraySet<String> outUsedLibraries)
10294            throws PackageManagerException {
10295        final int libCount = requestedLibraries.size();
10296        for (int i = 0; i < libCount; i++) {
10297            final String libName = requestedLibraries.get(i);
10298            final int libVersion = requiredVersions != null ? requiredVersions[i]
10299                    : SharedLibraryInfo.VERSION_UNDEFINED;
10300            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10301            if (libEntry == null) {
10302                if (required) {
10303                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10304                            "Package " + packageName + " requires unavailable shared library "
10305                                    + libName + "; failing!");
10306                } else if (DEBUG_SHARED_LIBRARIES) {
10307                    Slog.i(TAG, "Package " + packageName
10308                            + " desires unavailable shared library "
10309                            + libName + "; ignoring!");
10310                }
10311            } else {
10312                if (requiredVersions != null && requiredCertDigests != null) {
10313                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10314                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10315                            "Package " + packageName + " requires unavailable static shared"
10316                                    + " library " + libName + " version "
10317                                    + libEntry.info.getVersion() + "; failing!");
10318                    }
10319
10320                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10321                    if (libPkg == null) {
10322                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10323                                "Package " + packageName + " requires unavailable static shared"
10324                                        + " library; failing!");
10325                    }
10326
10327                    String expectedCertDigest = requiredCertDigests[i];
10328                    String libCertDigest = PackageUtils.computeCertSha256Digest(
10329                                libPkg.mSignatures[0]);
10330                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
10331                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10332                                "Package " + packageName + " requires differently signed" +
10333                                        " static shared library; failing!");
10334                    }
10335                }
10336
10337                if (outUsedLibraries == null) {
10338                    outUsedLibraries = new ArraySet<>();
10339                }
10340                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10341            }
10342        }
10343        return outUsedLibraries;
10344    }
10345
10346    private static boolean hasString(List<String> list, List<String> which) {
10347        if (list == null) {
10348            return false;
10349        }
10350        for (int i=list.size()-1; i>=0; i--) {
10351            for (int j=which.size()-1; j>=0; j--) {
10352                if (which.get(j).equals(list.get(i))) {
10353                    return true;
10354                }
10355            }
10356        }
10357        return false;
10358    }
10359
10360    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10361            PackageParser.Package changingPkg) {
10362        ArrayList<PackageParser.Package> res = null;
10363        for (PackageParser.Package pkg : mPackages.values()) {
10364            if (changingPkg != null
10365                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10366                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10367                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10368                            changingPkg.staticSharedLibName)) {
10369                return null;
10370            }
10371            if (res == null) {
10372                res = new ArrayList<>();
10373            }
10374            res.add(pkg);
10375            try {
10376                updateSharedLibrariesLPr(pkg, changingPkg);
10377            } catch (PackageManagerException e) {
10378                // If a system app update or an app and a required lib missing we
10379                // delete the package and for updated system apps keep the data as
10380                // it is better for the user to reinstall than to be in an limbo
10381                // state. Also libs disappearing under an app should never happen
10382                // - just in case.
10383                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10384                    final int flags = pkg.isUpdatedSystemApp()
10385                            ? PackageManager.DELETE_KEEP_DATA : 0;
10386                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10387                            flags , null, true, null);
10388                }
10389                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10390            }
10391        }
10392        return res;
10393    }
10394
10395    /**
10396     * Derive the value of the {@code cpuAbiOverride} based on the provided
10397     * value and an optional stored value from the package settings.
10398     */
10399    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10400        String cpuAbiOverride = null;
10401
10402        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10403            cpuAbiOverride = null;
10404        } else if (abiOverride != null) {
10405            cpuAbiOverride = abiOverride;
10406        } else if (settings != null) {
10407            cpuAbiOverride = settings.cpuAbiOverrideString;
10408        }
10409
10410        return cpuAbiOverride;
10411    }
10412
10413    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10414            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10415                    throws PackageManagerException {
10416        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10417        // If the package has children and this is the first dive in the function
10418        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10419        // whether all packages (parent and children) would be successfully scanned
10420        // before the actual scan since scanning mutates internal state and we want
10421        // to atomically install the package and its children.
10422        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10423            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10424                scanFlags |= SCAN_CHECK_ONLY;
10425            }
10426        } else {
10427            scanFlags &= ~SCAN_CHECK_ONLY;
10428        }
10429
10430        final PackageParser.Package scannedPkg;
10431        try {
10432            // Scan the parent
10433            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10434            // Scan the children
10435            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10436            for (int i = 0; i < childCount; i++) {
10437                PackageParser.Package childPkg = pkg.childPackages.get(i);
10438                scanPackageLI(childPkg, policyFlags,
10439                        scanFlags, currentTime, user);
10440            }
10441        } finally {
10442            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10443        }
10444
10445        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10446            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10447        }
10448
10449        return scannedPkg;
10450    }
10451
10452    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10453            int scanFlags, long currentTime, @Nullable UserHandle user)
10454                    throws PackageManagerException {
10455        boolean success = false;
10456        try {
10457            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10458                    currentTime, user);
10459            success = true;
10460            return res;
10461        } finally {
10462            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10463                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10464                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10465                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10466                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10467            }
10468        }
10469    }
10470
10471    /**
10472     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10473     */
10474    private static boolean apkHasCode(String fileName) {
10475        StrictJarFile jarFile = null;
10476        try {
10477            jarFile = new StrictJarFile(fileName,
10478                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10479            return jarFile.findEntry("classes.dex") != null;
10480        } catch (IOException ignore) {
10481        } finally {
10482            try {
10483                if (jarFile != null) {
10484                    jarFile.close();
10485                }
10486            } catch (IOException ignore) {}
10487        }
10488        return false;
10489    }
10490
10491    /**
10492     * Enforces code policy for the package. This ensures that if an APK has
10493     * declared hasCode="true" in its manifest that the APK actually contains
10494     * code.
10495     *
10496     * @throws PackageManagerException If bytecode could not be found when it should exist
10497     */
10498    private static void assertCodePolicy(PackageParser.Package pkg)
10499            throws PackageManagerException {
10500        final boolean shouldHaveCode =
10501                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10502        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10503            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10504                    "Package " + pkg.baseCodePath + " code is missing");
10505        }
10506
10507        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10508            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10509                final boolean splitShouldHaveCode =
10510                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10511                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10512                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10513                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10514                }
10515            }
10516        }
10517    }
10518
10519    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10520            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10521                    throws PackageManagerException {
10522        if (DEBUG_PACKAGE_SCANNING) {
10523            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10524                Log.d(TAG, "Scanning package " + pkg.packageName);
10525        }
10526
10527        applyPolicy(pkg, policyFlags);
10528
10529        assertPackageIsValid(pkg, policyFlags, scanFlags);
10530
10531        // Initialize package source and resource directories
10532        final File scanFile = new File(pkg.codePath);
10533        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10534        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10535
10536        SharedUserSetting suid = null;
10537        PackageSetting pkgSetting = null;
10538
10539        // Getting the package setting may have a side-effect, so if we
10540        // are only checking if scan would succeed, stash a copy of the
10541        // old setting to restore at the end.
10542        PackageSetting nonMutatedPs = null;
10543
10544        // We keep references to the derived CPU Abis from settings in oder to reuse
10545        // them in the case where we're not upgrading or booting for the first time.
10546        String primaryCpuAbiFromSettings = null;
10547        String secondaryCpuAbiFromSettings = null;
10548
10549        // writer
10550        synchronized (mPackages) {
10551            if (pkg.mSharedUserId != null) {
10552                // SIDE EFFECTS; may potentially allocate a new shared user
10553                suid = mSettings.getSharedUserLPw(
10554                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10555                if (DEBUG_PACKAGE_SCANNING) {
10556                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10557                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10558                                + "): packages=" + suid.packages);
10559                }
10560            }
10561
10562            // Check if we are renaming from an original package name.
10563            PackageSetting origPackage = null;
10564            String realName = null;
10565            if (pkg.mOriginalPackages != null) {
10566                // This package may need to be renamed to a previously
10567                // installed name.  Let's check on that...
10568                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10569                if (pkg.mOriginalPackages.contains(renamed)) {
10570                    // This package had originally been installed as the
10571                    // original name, and we have already taken care of
10572                    // transitioning to the new one.  Just update the new
10573                    // one to continue using the old name.
10574                    realName = pkg.mRealPackage;
10575                    if (!pkg.packageName.equals(renamed)) {
10576                        // Callers into this function may have already taken
10577                        // care of renaming the package; only do it here if
10578                        // it is not already done.
10579                        pkg.setPackageName(renamed);
10580                    }
10581                } else {
10582                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10583                        if ((origPackage = mSettings.getPackageLPr(
10584                                pkg.mOriginalPackages.get(i))) != null) {
10585                            // We do have the package already installed under its
10586                            // original name...  should we use it?
10587                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10588                                // New package is not compatible with original.
10589                                origPackage = null;
10590                                continue;
10591                            } else if (origPackage.sharedUser != null) {
10592                                // Make sure uid is compatible between packages.
10593                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10594                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10595                                            + " to " + pkg.packageName + ": old uid "
10596                                            + origPackage.sharedUser.name
10597                                            + " differs from " + pkg.mSharedUserId);
10598                                    origPackage = null;
10599                                    continue;
10600                                }
10601                                // TODO: Add case when shared user id is added [b/28144775]
10602                            } else {
10603                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10604                                        + pkg.packageName + " to old name " + origPackage.name);
10605                            }
10606                            break;
10607                        }
10608                    }
10609                }
10610            }
10611
10612            if (mTransferedPackages.contains(pkg.packageName)) {
10613                Slog.w(TAG, "Package " + pkg.packageName
10614                        + " was transferred to another, but its .apk remains");
10615            }
10616
10617            // See comments in nonMutatedPs declaration
10618            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10619                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10620                if (foundPs != null) {
10621                    nonMutatedPs = new PackageSetting(foundPs);
10622                }
10623            }
10624
10625            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10626                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10627                if (foundPs != null) {
10628                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10629                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10630                }
10631            }
10632
10633            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10634            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10635                PackageManagerService.reportSettingsProblem(Log.WARN,
10636                        "Package " + pkg.packageName + " shared user changed from "
10637                                + (pkgSetting.sharedUser != null
10638                                        ? pkgSetting.sharedUser.name : "<nothing>")
10639                                + " to "
10640                                + (suid != null ? suid.name : "<nothing>")
10641                                + "; replacing with new");
10642                pkgSetting = null;
10643            }
10644            final PackageSetting oldPkgSetting =
10645                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10646            final PackageSetting disabledPkgSetting =
10647                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10648
10649            String[] usesStaticLibraries = null;
10650            if (pkg.usesStaticLibraries != null) {
10651                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10652                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10653            }
10654
10655            if (pkgSetting == null) {
10656                final String parentPackageName = (pkg.parentPackage != null)
10657                        ? pkg.parentPackage.packageName : null;
10658                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10659                // REMOVE SharedUserSetting from method; update in a separate call
10660                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10661                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10662                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10663                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10664                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10665                        true /*allowInstall*/, instantApp, parentPackageName,
10666                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
10667                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10668                // SIDE EFFECTS; updates system state; move elsewhere
10669                if (origPackage != null) {
10670                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10671                }
10672                mSettings.addUserToSettingLPw(pkgSetting);
10673            } else {
10674                // REMOVE SharedUserSetting from method; update in a separate call.
10675                //
10676                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10677                // secondaryCpuAbi are not known at this point so we always update them
10678                // to null here, only to reset them at a later point.
10679                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10680                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10681                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10682                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10683                        UserManagerService.getInstance(), usesStaticLibraries,
10684                        pkg.usesStaticLibrariesVersions);
10685            }
10686            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10687            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10688
10689            // SIDE EFFECTS; modifies system state; move elsewhere
10690            if (pkgSetting.origPackage != null) {
10691                // If we are first transitioning from an original package,
10692                // fix up the new package's name now.  We need to do this after
10693                // looking up the package under its new name, so getPackageLP
10694                // can take care of fiddling things correctly.
10695                pkg.setPackageName(origPackage.name);
10696
10697                // File a report about this.
10698                String msg = "New package " + pkgSetting.realName
10699                        + " renamed to replace old package " + pkgSetting.name;
10700                reportSettingsProblem(Log.WARN, msg);
10701
10702                // Make a note of it.
10703                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10704                    mTransferedPackages.add(origPackage.name);
10705                }
10706
10707                // No longer need to retain this.
10708                pkgSetting.origPackage = null;
10709            }
10710
10711            // SIDE EFFECTS; modifies system state; move elsewhere
10712            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10713                // Make a note of it.
10714                mTransferedPackages.add(pkg.packageName);
10715            }
10716
10717            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10718                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10719            }
10720
10721            if ((scanFlags & SCAN_BOOTING) == 0
10722                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10723                // Check all shared libraries and map to their actual file path.
10724                // We only do this here for apps not on a system dir, because those
10725                // are the only ones that can fail an install due to this.  We
10726                // will take care of the system apps by updating all of their
10727                // library paths after the scan is done. Also during the initial
10728                // scan don't update any libs as we do this wholesale after all
10729                // apps are scanned to avoid dependency based scanning.
10730                updateSharedLibrariesLPr(pkg, null);
10731            }
10732
10733            if (mFoundPolicyFile) {
10734                SELinuxMMAC.assignSeInfoValue(pkg);
10735            }
10736            pkg.applicationInfo.uid = pkgSetting.appId;
10737            pkg.mExtras = pkgSetting;
10738
10739
10740            // Static shared libs have same package with different versions where
10741            // we internally use a synthetic package name to allow multiple versions
10742            // of the same package, therefore we need to compare signatures against
10743            // the package setting for the latest library version.
10744            PackageSetting signatureCheckPs = pkgSetting;
10745            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10746                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10747                if (libraryEntry != null) {
10748                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10749                }
10750            }
10751
10752            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10753                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10754                    // We just determined the app is signed correctly, so bring
10755                    // over the latest parsed certs.
10756                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10757                } else {
10758                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10759                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10760                                "Package " + pkg.packageName + " upgrade keys do not match the "
10761                                + "previously installed version");
10762                    } else {
10763                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10764                        String msg = "System package " + pkg.packageName
10765                                + " signature changed; retaining data.";
10766                        reportSettingsProblem(Log.WARN, msg);
10767                    }
10768                }
10769            } else {
10770                try {
10771                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10772                    verifySignaturesLP(signatureCheckPs, pkg);
10773                    // We just determined the app is signed correctly, so bring
10774                    // over the latest parsed certs.
10775                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10776                } catch (PackageManagerException e) {
10777                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10778                        throw e;
10779                    }
10780                    // The signature has changed, but this package is in the system
10781                    // image...  let's recover!
10782                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10783                    // However...  if this package is part of a shared user, but it
10784                    // doesn't match the signature of the shared user, let's fail.
10785                    // What this means is that you can't change the signatures
10786                    // associated with an overall shared user, which doesn't seem all
10787                    // that unreasonable.
10788                    if (signatureCheckPs.sharedUser != null) {
10789                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10790                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10791                            throw new PackageManagerException(
10792                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10793                                    "Signature mismatch for shared user: "
10794                                            + pkgSetting.sharedUser);
10795                        }
10796                    }
10797                    // File a report about this.
10798                    String msg = "System package " + pkg.packageName
10799                            + " signature changed; retaining data.";
10800                    reportSettingsProblem(Log.WARN, msg);
10801                }
10802            }
10803
10804            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10805                // This package wants to adopt ownership of permissions from
10806                // another package.
10807                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10808                    final String origName = pkg.mAdoptPermissions.get(i);
10809                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10810                    if (orig != null) {
10811                        if (verifyPackageUpdateLPr(orig, pkg)) {
10812                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10813                                    + pkg.packageName);
10814                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10815                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10816                        }
10817                    }
10818                }
10819            }
10820        }
10821
10822        pkg.applicationInfo.processName = fixProcessName(
10823                pkg.applicationInfo.packageName,
10824                pkg.applicationInfo.processName);
10825
10826        if (pkg != mPlatformPackage) {
10827            // Get all of our default paths setup
10828            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10829        }
10830
10831        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10832
10833        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10834            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10835                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10836                final boolean extractNativeLibs = !pkg.isLibrary();
10837                derivePackageAbi(pkg, scanFile, cpuAbiOverride, extractNativeLibs,
10838                        mAppLib32InstallDir);
10839                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10840
10841                // Some system apps still use directory structure for native libraries
10842                // in which case we might end up not detecting abi solely based on apk
10843                // structure. Try to detect abi based on directory structure.
10844                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10845                        pkg.applicationInfo.primaryCpuAbi == null) {
10846                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10847                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10848                }
10849            } else {
10850                // This is not a first boot or an upgrade, don't bother deriving the
10851                // ABI during the scan. Instead, trust the value that was stored in the
10852                // package setting.
10853                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10854                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10855
10856                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10857
10858                if (DEBUG_ABI_SELECTION) {
10859                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10860                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10861                        pkg.applicationInfo.secondaryCpuAbi);
10862                }
10863            }
10864        } else {
10865            if ((scanFlags & SCAN_MOVE) != 0) {
10866                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10867                // but we already have this packages package info in the PackageSetting. We just
10868                // use that and derive the native library path based on the new codepath.
10869                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10870                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10871            }
10872
10873            // Set native library paths again. For moves, the path will be updated based on the
10874            // ABIs we've determined above. For non-moves, the path will be updated based on the
10875            // ABIs we determined during compilation, but the path will depend on the final
10876            // package path (after the rename away from the stage path).
10877            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10878        }
10879
10880        // This is a special case for the "system" package, where the ABI is
10881        // dictated by the zygote configuration (and init.rc). We should keep track
10882        // of this ABI so that we can deal with "normal" applications that run under
10883        // the same UID correctly.
10884        if (mPlatformPackage == pkg) {
10885            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10886                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10887        }
10888
10889        // If there's a mismatch between the abi-override in the package setting
10890        // and the abiOverride specified for the install. Warn about this because we
10891        // would've already compiled the app without taking the package setting into
10892        // account.
10893        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10894            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10895                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10896                        " for package " + pkg.packageName);
10897            }
10898        }
10899
10900        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10901        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10902        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10903
10904        // Copy the derived override back to the parsed package, so that we can
10905        // update the package settings accordingly.
10906        pkg.cpuAbiOverride = cpuAbiOverride;
10907
10908        if (DEBUG_ABI_SELECTION) {
10909            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10910                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10911                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10912        }
10913
10914        // Push the derived path down into PackageSettings so we know what to
10915        // clean up at uninstall time.
10916        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10917
10918        if (DEBUG_ABI_SELECTION) {
10919            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10920                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10921                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10922        }
10923
10924        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10925        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10926            // We don't do this here during boot because we can do it all
10927            // at once after scanning all existing packages.
10928            //
10929            // We also do this *before* we perform dexopt on this package, so that
10930            // we can avoid redundant dexopts, and also to make sure we've got the
10931            // code and package path correct.
10932            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10933        }
10934
10935        if (mFactoryTest && pkg.requestedPermissions.contains(
10936                android.Manifest.permission.FACTORY_TEST)) {
10937            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10938        }
10939
10940        if (isSystemApp(pkg)) {
10941            pkgSetting.isOrphaned = true;
10942        }
10943
10944        // Take care of first install / last update times.
10945        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10946        if (currentTime != 0) {
10947            if (pkgSetting.firstInstallTime == 0) {
10948                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10949            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10950                pkgSetting.lastUpdateTime = currentTime;
10951            }
10952        } else if (pkgSetting.firstInstallTime == 0) {
10953            // We need *something*.  Take time time stamp of the file.
10954            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10955        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10956            if (scanFileTime != pkgSetting.timeStamp) {
10957                // A package on the system image has changed; consider this
10958                // to be an update.
10959                pkgSetting.lastUpdateTime = scanFileTime;
10960            }
10961        }
10962        pkgSetting.setTimeStamp(scanFileTime);
10963
10964        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10965            if (nonMutatedPs != null) {
10966                synchronized (mPackages) {
10967                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10968                }
10969            }
10970        } else {
10971            final int userId = user == null ? 0 : user.getIdentifier();
10972            // Modify state for the given package setting
10973            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10974                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10975            if (pkgSetting.getInstantApp(userId)) {
10976                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10977            }
10978        }
10979        return pkg;
10980    }
10981
10982    /**
10983     * Applies policy to the parsed package based upon the given policy flags.
10984     * Ensures the package is in a good state.
10985     * <p>
10986     * Implementation detail: This method must NOT have any side effect. It would
10987     * ideally be static, but, it requires locks to read system state.
10988     */
10989    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10990        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10991            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10992            if (pkg.applicationInfo.isDirectBootAware()) {
10993                // we're direct boot aware; set for all components
10994                for (PackageParser.Service s : pkg.services) {
10995                    s.info.encryptionAware = s.info.directBootAware = true;
10996                }
10997                for (PackageParser.Provider p : pkg.providers) {
10998                    p.info.encryptionAware = p.info.directBootAware = true;
10999                }
11000                for (PackageParser.Activity a : pkg.activities) {
11001                    a.info.encryptionAware = a.info.directBootAware = true;
11002                }
11003                for (PackageParser.Activity r : pkg.receivers) {
11004                    r.info.encryptionAware = r.info.directBootAware = true;
11005                }
11006            }
11007            if (compressedFileExists(pkg.baseCodePath)) {
11008                pkg.isStub = true;
11009            }
11010        } else {
11011            // Only allow system apps to be flagged as core apps.
11012            pkg.coreApp = false;
11013            // clear flags not applicable to regular apps
11014            pkg.applicationInfo.privateFlags &=
11015                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
11016            pkg.applicationInfo.privateFlags &=
11017                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
11018        }
11019        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
11020
11021        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
11022            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
11023        }
11024
11025        if (!isSystemApp(pkg)) {
11026            // Only system apps can use these features.
11027            pkg.mOriginalPackages = null;
11028            pkg.mRealPackage = null;
11029            pkg.mAdoptPermissions = null;
11030        }
11031    }
11032
11033    /**
11034     * Asserts the parsed package is valid according to the given policy. If the
11035     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
11036     * <p>
11037     * Implementation detail: This method must NOT have any side effects. It would
11038     * ideally be static, but, it requires locks to read system state.
11039     *
11040     * @throws PackageManagerException If the package fails any of the validation checks
11041     */
11042    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
11043            throws PackageManagerException {
11044        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
11045            assertCodePolicy(pkg);
11046        }
11047
11048        if (pkg.applicationInfo.getCodePath() == null ||
11049                pkg.applicationInfo.getResourcePath() == null) {
11050            // Bail out. The resource and code paths haven't been set.
11051            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
11052                    "Code and resource paths haven't been set correctly");
11053        }
11054
11055        // Make sure we're not adding any bogus keyset info
11056        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11057        ksms.assertScannedPackageValid(pkg);
11058
11059        synchronized (mPackages) {
11060            // The special "android" package can only be defined once
11061            if (pkg.packageName.equals("android")) {
11062                if (mAndroidApplication != null) {
11063                    Slog.w(TAG, "*************************************************");
11064                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
11065                    Slog.w(TAG, " codePath=" + pkg.codePath);
11066                    Slog.w(TAG, "*************************************************");
11067                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11068                            "Core android package being redefined.  Skipping.");
11069                }
11070            }
11071
11072            // A package name must be unique; don't allow duplicates
11073            if (mPackages.containsKey(pkg.packageName)) {
11074                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11075                        "Application package " + pkg.packageName
11076                        + " already installed.  Skipping duplicate.");
11077            }
11078
11079            if (pkg.applicationInfo.isStaticSharedLibrary()) {
11080                // Static libs have a synthetic package name containing the version
11081                // but we still want the base name to be unique.
11082                if (mPackages.containsKey(pkg.manifestPackageName)) {
11083                    throw new PackageManagerException(
11084                            "Duplicate static shared lib provider package");
11085                }
11086
11087                // Static shared libraries should have at least O target SDK
11088                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
11089                    throw new PackageManagerException(
11090                            "Packages declaring static-shared libs must target O SDK or higher");
11091                }
11092
11093                // Package declaring static a shared lib cannot be instant apps
11094                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11095                    throw new PackageManagerException(
11096                            "Packages declaring static-shared libs cannot be instant apps");
11097                }
11098
11099                // Package declaring static a shared lib cannot be renamed since the package
11100                // name is synthetic and apps can't code around package manager internals.
11101                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
11102                    throw new PackageManagerException(
11103                            "Packages declaring static-shared libs cannot be renamed");
11104                }
11105
11106                // Package declaring static a shared lib cannot declare child packages
11107                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
11108                    throw new PackageManagerException(
11109                            "Packages declaring static-shared libs cannot have child packages");
11110                }
11111
11112                // Package declaring static a shared lib cannot declare dynamic libs
11113                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
11114                    throw new PackageManagerException(
11115                            "Packages declaring static-shared libs cannot declare dynamic libs");
11116                }
11117
11118                // Package declaring static a shared lib cannot declare shared users
11119                if (pkg.mSharedUserId != null) {
11120                    throw new PackageManagerException(
11121                            "Packages declaring static-shared libs cannot declare shared users");
11122                }
11123
11124                // Static shared libs cannot declare activities
11125                if (!pkg.activities.isEmpty()) {
11126                    throw new PackageManagerException(
11127                            "Static shared libs cannot declare activities");
11128                }
11129
11130                // Static shared libs cannot declare services
11131                if (!pkg.services.isEmpty()) {
11132                    throw new PackageManagerException(
11133                            "Static shared libs cannot declare services");
11134                }
11135
11136                // Static shared libs cannot declare providers
11137                if (!pkg.providers.isEmpty()) {
11138                    throw new PackageManagerException(
11139                            "Static shared libs cannot declare content providers");
11140                }
11141
11142                // Static shared libs cannot declare receivers
11143                if (!pkg.receivers.isEmpty()) {
11144                    throw new PackageManagerException(
11145                            "Static shared libs cannot declare broadcast receivers");
11146                }
11147
11148                // Static shared libs cannot declare permission groups
11149                if (!pkg.permissionGroups.isEmpty()) {
11150                    throw new PackageManagerException(
11151                            "Static shared libs cannot declare permission groups");
11152                }
11153
11154                // Static shared libs cannot declare permissions
11155                if (!pkg.permissions.isEmpty()) {
11156                    throw new PackageManagerException(
11157                            "Static shared libs cannot declare permissions");
11158                }
11159
11160                // Static shared libs cannot declare protected broadcasts
11161                if (pkg.protectedBroadcasts != null) {
11162                    throw new PackageManagerException(
11163                            "Static shared libs cannot declare protected broadcasts");
11164                }
11165
11166                // Static shared libs cannot be overlay targets
11167                if (pkg.mOverlayTarget != null) {
11168                    throw new PackageManagerException(
11169                            "Static shared libs cannot be overlay targets");
11170                }
11171
11172                // The version codes must be ordered as lib versions
11173                int minVersionCode = Integer.MIN_VALUE;
11174                int maxVersionCode = Integer.MAX_VALUE;
11175
11176                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
11177                        pkg.staticSharedLibName);
11178                if (versionedLib != null) {
11179                    final int versionCount = versionedLib.size();
11180                    for (int i = 0; i < versionCount; i++) {
11181                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
11182                        final int libVersionCode = libInfo.getDeclaringPackage()
11183                                .getVersionCode();
11184                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
11185                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
11186                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
11187                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
11188                        } else {
11189                            minVersionCode = maxVersionCode = libVersionCode;
11190                            break;
11191                        }
11192                    }
11193                }
11194                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
11195                    throw new PackageManagerException("Static shared"
11196                            + " lib version codes must be ordered as lib versions");
11197                }
11198            }
11199
11200            // Only privileged apps and updated privileged apps can add child packages.
11201            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
11202                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
11203                    throw new PackageManagerException("Only privileged apps can add child "
11204                            + "packages. Ignoring package " + pkg.packageName);
11205                }
11206                final int childCount = pkg.childPackages.size();
11207                for (int i = 0; i < childCount; i++) {
11208                    PackageParser.Package childPkg = pkg.childPackages.get(i);
11209                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
11210                            childPkg.packageName)) {
11211                        throw new PackageManagerException("Can't override child of "
11212                                + "another disabled app. Ignoring package " + pkg.packageName);
11213                    }
11214                }
11215            }
11216
11217            // If we're only installing presumed-existing packages, require that the
11218            // scanned APK is both already known and at the path previously established
11219            // for it.  Previously unknown packages we pick up normally, but if we have an
11220            // a priori expectation about this package's install presence, enforce it.
11221            // With a singular exception for new system packages. When an OTA contains
11222            // a new system package, we allow the codepath to change from a system location
11223            // to the user-installed location. If we don't allow this change, any newer,
11224            // user-installed version of the application will be ignored.
11225            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11226                if (mExpectingBetter.containsKey(pkg.packageName)) {
11227                    logCriticalInfo(Log.WARN,
11228                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11229                } else {
11230                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11231                    if (known != null) {
11232                        if (DEBUG_PACKAGE_SCANNING) {
11233                            Log.d(TAG, "Examining " + pkg.codePath
11234                                    + " and requiring known paths " + known.codePathString
11235                                    + " & " + known.resourcePathString);
11236                        }
11237                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11238                                || !pkg.applicationInfo.getResourcePath().equals(
11239                                        known.resourcePathString)) {
11240                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11241                                    "Application package " + pkg.packageName
11242                                    + " found at " + pkg.applicationInfo.getCodePath()
11243                                    + " but expected at " + known.codePathString
11244                                    + "; ignoring.");
11245                        }
11246                    }
11247                }
11248            }
11249
11250            // Verify that this new package doesn't have any content providers
11251            // that conflict with existing packages.  Only do this if the
11252            // package isn't already installed, since we don't want to break
11253            // things that are installed.
11254            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11255                final int N = pkg.providers.size();
11256                int i;
11257                for (i=0; i<N; i++) {
11258                    PackageParser.Provider p = pkg.providers.get(i);
11259                    if (p.info.authority != null) {
11260                        String names[] = p.info.authority.split(";");
11261                        for (int j = 0; j < names.length; j++) {
11262                            if (mProvidersByAuthority.containsKey(names[j])) {
11263                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11264                                final String otherPackageName =
11265                                        ((other != null && other.getComponentName() != null) ?
11266                                                other.getComponentName().getPackageName() : "?");
11267                                throw new PackageManagerException(
11268                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11269                                        "Can't install because provider name " + names[j]
11270                                                + " (in package " + pkg.applicationInfo.packageName
11271                                                + ") is already used by " + otherPackageName);
11272                            }
11273                        }
11274                    }
11275                }
11276            }
11277        }
11278    }
11279
11280    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
11281            int type, String declaringPackageName, int declaringVersionCode) {
11282        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11283        if (versionedLib == null) {
11284            versionedLib = new SparseArray<>();
11285            mSharedLibraries.put(name, versionedLib);
11286            if (type == SharedLibraryInfo.TYPE_STATIC) {
11287                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11288            }
11289        } else if (versionedLib.indexOfKey(version) >= 0) {
11290            return false;
11291        }
11292        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11293                version, type, declaringPackageName, declaringVersionCode);
11294        versionedLib.put(version, libEntry);
11295        return true;
11296    }
11297
11298    private boolean removeSharedLibraryLPw(String name, int version) {
11299        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11300        if (versionedLib == null) {
11301            return false;
11302        }
11303        final int libIdx = versionedLib.indexOfKey(version);
11304        if (libIdx < 0) {
11305            return false;
11306        }
11307        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11308        versionedLib.remove(version);
11309        if (versionedLib.size() <= 0) {
11310            mSharedLibraries.remove(name);
11311            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11312                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11313                        .getPackageName());
11314            }
11315        }
11316        return true;
11317    }
11318
11319    /**
11320     * Adds a scanned package to the system. When this method is finished, the package will
11321     * be available for query, resolution, etc...
11322     */
11323    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11324            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11325        final String pkgName = pkg.packageName;
11326        if (mCustomResolverComponentName != null &&
11327                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11328            setUpCustomResolverActivity(pkg);
11329        }
11330
11331        if (pkg.packageName.equals("android")) {
11332            synchronized (mPackages) {
11333                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11334                    // Set up information for our fall-back user intent resolution activity.
11335                    mPlatformPackage = pkg;
11336                    pkg.mVersionCode = mSdkVersion;
11337                    mAndroidApplication = pkg.applicationInfo;
11338                    if (!mResolverReplaced) {
11339                        mResolveActivity.applicationInfo = mAndroidApplication;
11340                        mResolveActivity.name = ResolverActivity.class.getName();
11341                        mResolveActivity.packageName = mAndroidApplication.packageName;
11342                        mResolveActivity.processName = "system:ui";
11343                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11344                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11345                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11346                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11347                        mResolveActivity.exported = true;
11348                        mResolveActivity.enabled = true;
11349                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11350                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11351                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11352                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11353                                | ActivityInfo.CONFIG_ORIENTATION
11354                                | ActivityInfo.CONFIG_KEYBOARD
11355                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11356                        mResolveInfo.activityInfo = mResolveActivity;
11357                        mResolveInfo.priority = 0;
11358                        mResolveInfo.preferredOrder = 0;
11359                        mResolveInfo.match = 0;
11360                        mResolveComponentName = new ComponentName(
11361                                mAndroidApplication.packageName, mResolveActivity.name);
11362                    }
11363                }
11364            }
11365        }
11366
11367        ArrayList<PackageParser.Package> clientLibPkgs = null;
11368        // writer
11369        synchronized (mPackages) {
11370            boolean hasStaticSharedLibs = false;
11371
11372            // Any app can add new static shared libraries
11373            if (pkg.staticSharedLibName != null) {
11374                // Static shared libs don't allow renaming as they have synthetic package
11375                // names to allow install of multiple versions, so use name from manifest.
11376                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11377                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11378                        pkg.manifestPackageName, pkg.mVersionCode)) {
11379                    hasStaticSharedLibs = true;
11380                } else {
11381                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11382                                + pkg.staticSharedLibName + " already exists; skipping");
11383                }
11384                // Static shared libs cannot be updated once installed since they
11385                // use synthetic package name which includes the version code, so
11386                // not need to update other packages's shared lib dependencies.
11387            }
11388
11389            if (!hasStaticSharedLibs
11390                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11391                // Only system apps can add new dynamic shared libraries.
11392                if (pkg.libraryNames != null) {
11393                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11394                        String name = pkg.libraryNames.get(i);
11395                        boolean allowed = false;
11396                        if (pkg.isUpdatedSystemApp()) {
11397                            // New library entries can only be added through the
11398                            // system image.  This is important to get rid of a lot
11399                            // of nasty edge cases: for example if we allowed a non-
11400                            // system update of the app to add a library, then uninstalling
11401                            // the update would make the library go away, and assumptions
11402                            // we made such as through app install filtering would now
11403                            // have allowed apps on the device which aren't compatible
11404                            // with it.  Better to just have the restriction here, be
11405                            // conservative, and create many fewer cases that can negatively
11406                            // impact the user experience.
11407                            final PackageSetting sysPs = mSettings
11408                                    .getDisabledSystemPkgLPr(pkg.packageName);
11409                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11410                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11411                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11412                                        allowed = true;
11413                                        break;
11414                                    }
11415                                }
11416                            }
11417                        } else {
11418                            allowed = true;
11419                        }
11420                        if (allowed) {
11421                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11422                                    SharedLibraryInfo.VERSION_UNDEFINED,
11423                                    SharedLibraryInfo.TYPE_DYNAMIC,
11424                                    pkg.packageName, pkg.mVersionCode)) {
11425                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11426                                        + name + " already exists; skipping");
11427                            }
11428                        } else {
11429                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11430                                    + name + " that is not declared on system image; skipping");
11431                        }
11432                    }
11433
11434                    if ((scanFlags & SCAN_BOOTING) == 0) {
11435                        // If we are not booting, we need to update any applications
11436                        // that are clients of our shared library.  If we are booting,
11437                        // this will all be done once the scan is complete.
11438                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11439                    }
11440                }
11441            }
11442        }
11443
11444        if ((scanFlags & SCAN_BOOTING) != 0) {
11445            // No apps can run during boot scan, so they don't need to be frozen
11446        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11447            // Caller asked to not kill app, so it's probably not frozen
11448        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11449            // Caller asked us to ignore frozen check for some reason; they
11450            // probably didn't know the package name
11451        } else {
11452            // We're doing major surgery on this package, so it better be frozen
11453            // right now to keep it from launching
11454            checkPackageFrozen(pkgName);
11455        }
11456
11457        // Also need to kill any apps that are dependent on the library.
11458        if (clientLibPkgs != null) {
11459            for (int i=0; i<clientLibPkgs.size(); i++) {
11460                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11461                killApplication(clientPkg.applicationInfo.packageName,
11462                        clientPkg.applicationInfo.uid, "update lib");
11463            }
11464        }
11465
11466        // writer
11467        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11468
11469        synchronized (mPackages) {
11470            // We don't expect installation to fail beyond this point
11471
11472            // Add the new setting to mSettings
11473            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11474            // Add the new setting to mPackages
11475            mPackages.put(pkg.applicationInfo.packageName, pkg);
11476            // Make sure we don't accidentally delete its data.
11477            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11478            while (iter.hasNext()) {
11479                PackageCleanItem item = iter.next();
11480                if (pkgName.equals(item.packageName)) {
11481                    iter.remove();
11482                }
11483            }
11484
11485            // Add the package's KeySets to the global KeySetManagerService
11486            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11487            ksms.addScannedPackageLPw(pkg);
11488
11489            int N = pkg.providers.size();
11490            StringBuilder r = null;
11491            int i;
11492            for (i=0; i<N; i++) {
11493                PackageParser.Provider p = pkg.providers.get(i);
11494                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11495                        p.info.processName);
11496                mProviders.addProvider(p);
11497                p.syncable = p.info.isSyncable;
11498                if (p.info.authority != null) {
11499                    String names[] = p.info.authority.split(";");
11500                    p.info.authority = null;
11501                    for (int j = 0; j < names.length; j++) {
11502                        if (j == 1 && p.syncable) {
11503                            // We only want the first authority for a provider to possibly be
11504                            // syncable, so if we already added this provider using a different
11505                            // authority clear the syncable flag. We copy the provider before
11506                            // changing it because the mProviders object contains a reference
11507                            // to a provider that we don't want to change.
11508                            // Only do this for the second authority since the resulting provider
11509                            // object can be the same for all future authorities for this provider.
11510                            p = new PackageParser.Provider(p);
11511                            p.syncable = false;
11512                        }
11513                        if (!mProvidersByAuthority.containsKey(names[j])) {
11514                            mProvidersByAuthority.put(names[j], p);
11515                            if (p.info.authority == null) {
11516                                p.info.authority = names[j];
11517                            } else {
11518                                p.info.authority = p.info.authority + ";" + names[j];
11519                            }
11520                            if (DEBUG_PACKAGE_SCANNING) {
11521                                if (chatty)
11522                                    Log.d(TAG, "Registered content provider: " + names[j]
11523                                            + ", className = " + p.info.name + ", isSyncable = "
11524                                            + p.info.isSyncable);
11525                            }
11526                        } else {
11527                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11528                            Slog.w(TAG, "Skipping provider name " + names[j] +
11529                                    " (in package " + pkg.applicationInfo.packageName +
11530                                    "): name already used by "
11531                                    + ((other != null && other.getComponentName() != null)
11532                                            ? other.getComponentName().getPackageName() : "?"));
11533                        }
11534                    }
11535                }
11536                if (chatty) {
11537                    if (r == null) {
11538                        r = new StringBuilder(256);
11539                    } else {
11540                        r.append(' ');
11541                    }
11542                    r.append(p.info.name);
11543                }
11544            }
11545            if (r != null) {
11546                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11547            }
11548
11549            N = pkg.services.size();
11550            r = null;
11551            for (i=0; i<N; i++) {
11552                PackageParser.Service s = pkg.services.get(i);
11553                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11554                        s.info.processName);
11555                mServices.addService(s);
11556                if (chatty) {
11557                    if (r == null) {
11558                        r = new StringBuilder(256);
11559                    } else {
11560                        r.append(' ');
11561                    }
11562                    r.append(s.info.name);
11563                }
11564            }
11565            if (r != null) {
11566                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11567            }
11568
11569            N = pkg.receivers.size();
11570            r = null;
11571            for (i=0; i<N; i++) {
11572                PackageParser.Activity a = pkg.receivers.get(i);
11573                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11574                        a.info.processName);
11575                mReceivers.addActivity(a, "receiver");
11576                if (chatty) {
11577                    if (r == null) {
11578                        r = new StringBuilder(256);
11579                    } else {
11580                        r.append(' ');
11581                    }
11582                    r.append(a.info.name);
11583                }
11584            }
11585            if (r != null) {
11586                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11587            }
11588
11589            N = pkg.activities.size();
11590            r = null;
11591            for (i=0; i<N; i++) {
11592                PackageParser.Activity a = pkg.activities.get(i);
11593                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11594                        a.info.processName);
11595                mActivities.addActivity(a, "activity");
11596                if (chatty) {
11597                    if (r == null) {
11598                        r = new StringBuilder(256);
11599                    } else {
11600                        r.append(' ');
11601                    }
11602                    r.append(a.info.name);
11603                }
11604            }
11605            if (r != null) {
11606                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11607            }
11608
11609            N = pkg.permissionGroups.size();
11610            r = null;
11611            for (i=0; i<N; i++) {
11612                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11613                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11614                final String curPackageName = cur == null ? null : cur.info.packageName;
11615                // Dont allow ephemeral apps to define new permission groups.
11616                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11617                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11618                            + pg.info.packageName
11619                            + " ignored: instant apps cannot define new permission groups.");
11620                    continue;
11621                }
11622                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11623                if (cur == null || isPackageUpdate) {
11624                    mPermissionGroups.put(pg.info.name, pg);
11625                    if (chatty) {
11626                        if (r == null) {
11627                            r = new StringBuilder(256);
11628                        } else {
11629                            r.append(' ');
11630                        }
11631                        if (isPackageUpdate) {
11632                            r.append("UPD:");
11633                        }
11634                        r.append(pg.info.name);
11635                    }
11636                } else {
11637                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11638                            + pg.info.packageName + " ignored: original from "
11639                            + cur.info.packageName);
11640                    if (chatty) {
11641                        if (r == null) {
11642                            r = new StringBuilder(256);
11643                        } else {
11644                            r.append(' ');
11645                        }
11646                        r.append("DUP:");
11647                        r.append(pg.info.name);
11648                    }
11649                }
11650            }
11651            if (r != null) {
11652                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11653            }
11654
11655            N = pkg.permissions.size();
11656            r = null;
11657            for (i=0; i<N; i++) {
11658                PackageParser.Permission p = pkg.permissions.get(i);
11659
11660                // Dont allow ephemeral apps to define new permissions.
11661                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11662                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11663                            + p.info.packageName
11664                            + " ignored: instant apps cannot define new permissions.");
11665                    continue;
11666                }
11667
11668                // Assume by default that we did not install this permission into the system.
11669                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11670
11671                // Now that permission groups have a special meaning, we ignore permission
11672                // groups for legacy apps to prevent unexpected behavior. In particular,
11673                // permissions for one app being granted to someone just because they happen
11674                // to be in a group defined by another app (before this had no implications).
11675                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11676                    p.group = mPermissionGroups.get(p.info.group);
11677                    // Warn for a permission in an unknown group.
11678                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11679                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11680                                + p.info.packageName + " in an unknown group " + p.info.group);
11681                    }
11682                }
11683
11684                ArrayMap<String, BasePermission> permissionMap =
11685                        p.tree ? mSettings.mPermissionTrees
11686                                : mSettings.mPermissions;
11687                BasePermission bp = permissionMap.get(p.info.name);
11688
11689                // Allow system apps to redefine non-system permissions
11690                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11691                    final boolean currentOwnerIsSystem = (bp.perm != null
11692                            && isSystemApp(bp.perm.owner));
11693                    if (isSystemApp(p.owner)) {
11694                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11695                            // It's a built-in permission and no owner, take ownership now
11696                            bp.packageSetting = pkgSetting;
11697                            bp.perm = p;
11698                            bp.uid = pkg.applicationInfo.uid;
11699                            bp.sourcePackage = p.info.packageName;
11700                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11701                        } else if (!currentOwnerIsSystem) {
11702                            String msg = "New decl " + p.owner + " of permission  "
11703                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11704                            reportSettingsProblem(Log.WARN, msg);
11705                            bp = null;
11706                        }
11707                    }
11708                }
11709
11710                if (bp == null) {
11711                    bp = new BasePermission(p.info.name, p.info.packageName,
11712                            BasePermission.TYPE_NORMAL);
11713                    permissionMap.put(p.info.name, bp);
11714                }
11715
11716                if (bp.perm == null) {
11717                    if (bp.sourcePackage == null
11718                            || bp.sourcePackage.equals(p.info.packageName)) {
11719                        BasePermission tree = findPermissionTreeLP(p.info.name);
11720                        if (tree == null
11721                                || tree.sourcePackage.equals(p.info.packageName)) {
11722                            bp.packageSetting = pkgSetting;
11723                            bp.perm = p;
11724                            bp.uid = pkg.applicationInfo.uid;
11725                            bp.sourcePackage = p.info.packageName;
11726                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11727                            if (chatty) {
11728                                if (r == null) {
11729                                    r = new StringBuilder(256);
11730                                } else {
11731                                    r.append(' ');
11732                                }
11733                                r.append(p.info.name);
11734                            }
11735                        } else {
11736                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11737                                    + p.info.packageName + " ignored: base tree "
11738                                    + tree.name + " is from package "
11739                                    + tree.sourcePackage);
11740                        }
11741                    } else {
11742                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11743                                + p.info.packageName + " ignored: original from "
11744                                + bp.sourcePackage);
11745                    }
11746                } else if (chatty) {
11747                    if (r == null) {
11748                        r = new StringBuilder(256);
11749                    } else {
11750                        r.append(' ');
11751                    }
11752                    r.append("DUP:");
11753                    r.append(p.info.name);
11754                }
11755                if (bp.perm == p) {
11756                    bp.protectionLevel = p.info.protectionLevel;
11757                }
11758            }
11759
11760            if (r != null) {
11761                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11762            }
11763
11764            N = pkg.instrumentation.size();
11765            r = null;
11766            for (i=0; i<N; i++) {
11767                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11768                a.info.packageName = pkg.applicationInfo.packageName;
11769                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11770                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11771                a.info.splitNames = pkg.splitNames;
11772                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11773                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11774                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11775                a.info.dataDir = pkg.applicationInfo.dataDir;
11776                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11777                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11778                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11779                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11780                mInstrumentation.put(a.getComponentName(), a);
11781                if (chatty) {
11782                    if (r == null) {
11783                        r = new StringBuilder(256);
11784                    } else {
11785                        r.append(' ');
11786                    }
11787                    r.append(a.info.name);
11788                }
11789            }
11790            if (r != null) {
11791                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11792            }
11793
11794            if (pkg.protectedBroadcasts != null) {
11795                N = pkg.protectedBroadcasts.size();
11796                synchronized (mProtectedBroadcasts) {
11797                    for (i = 0; i < N; i++) {
11798                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11799                    }
11800                }
11801            }
11802        }
11803
11804        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11805    }
11806
11807    /**
11808     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11809     * is derived purely on the basis of the contents of {@code scanFile} and
11810     * {@code cpuAbiOverride}.
11811     *
11812     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11813     */
11814    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11815                                 String cpuAbiOverride, boolean extractLibs,
11816                                 File appLib32InstallDir)
11817            throws PackageManagerException {
11818        // Give ourselves some initial paths; we'll come back for another
11819        // pass once we've determined ABI below.
11820        setNativeLibraryPaths(pkg, appLib32InstallDir);
11821
11822        // We would never need to extract libs for forward-locked and external packages,
11823        // since the container service will do it for us. We shouldn't attempt to
11824        // extract libs from system app when it was not updated.
11825        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11826                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11827            extractLibs = false;
11828        }
11829
11830        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11831        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11832
11833        NativeLibraryHelper.Handle handle = null;
11834        try {
11835            handle = NativeLibraryHelper.Handle.create(pkg);
11836            // TODO(multiArch): This can be null for apps that didn't go through the
11837            // usual installation process. We can calculate it again, like we
11838            // do during install time.
11839            //
11840            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11841            // unnecessary.
11842            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11843
11844            // Null out the abis so that they can be recalculated.
11845            pkg.applicationInfo.primaryCpuAbi = null;
11846            pkg.applicationInfo.secondaryCpuAbi = null;
11847            if (isMultiArch(pkg.applicationInfo)) {
11848                // Warn if we've set an abiOverride for multi-lib packages..
11849                // By definition, we need to copy both 32 and 64 bit libraries for
11850                // such packages.
11851                if (pkg.cpuAbiOverride != null
11852                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11853                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11854                }
11855
11856                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11857                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11858                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11859                    if (extractLibs) {
11860                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11861                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11862                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11863                                useIsaSpecificSubdirs);
11864                    } else {
11865                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11866                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11867                    }
11868                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11869                }
11870
11871                // Shared library native code should be in the APK zip aligned
11872                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11873                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11874                            "Shared library native lib extraction not supported");
11875                }
11876
11877                maybeThrowExceptionForMultiArchCopy(
11878                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11879
11880                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11881                    if (extractLibs) {
11882                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11883                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11884                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11885                                useIsaSpecificSubdirs);
11886                    } else {
11887                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11888                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11889                    }
11890                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11891                }
11892
11893                maybeThrowExceptionForMultiArchCopy(
11894                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11895
11896                if (abi64 >= 0) {
11897                    // Shared library native libs should be in the APK zip aligned
11898                    if (extractLibs && pkg.isLibrary()) {
11899                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11900                                "Shared library native lib extraction not supported");
11901                    }
11902                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11903                }
11904
11905                if (abi32 >= 0) {
11906                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11907                    if (abi64 >= 0) {
11908                        if (pkg.use32bitAbi) {
11909                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11910                            pkg.applicationInfo.primaryCpuAbi = abi;
11911                        } else {
11912                            pkg.applicationInfo.secondaryCpuAbi = abi;
11913                        }
11914                    } else {
11915                        pkg.applicationInfo.primaryCpuAbi = abi;
11916                    }
11917                }
11918            } else {
11919                String[] abiList = (cpuAbiOverride != null) ?
11920                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11921
11922                // Enable gross and lame hacks for apps that are built with old
11923                // SDK tools. We must scan their APKs for renderscript bitcode and
11924                // not launch them if it's present. Don't bother checking on devices
11925                // that don't have 64 bit support.
11926                boolean needsRenderScriptOverride = false;
11927                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11928                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11929                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11930                    needsRenderScriptOverride = true;
11931                }
11932
11933                final int copyRet;
11934                if (extractLibs) {
11935                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11936                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11937                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11938                } else {
11939                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11940                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11941                }
11942                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11943
11944                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11945                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11946                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11947                }
11948
11949                if (copyRet >= 0) {
11950                    // Shared libraries that have native libs must be multi-architecture
11951                    if (pkg.isLibrary()) {
11952                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11953                                "Shared library with native libs must be multiarch");
11954                    }
11955                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11956                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11957                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11958                } else if (needsRenderScriptOverride) {
11959                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11960                }
11961            }
11962        } catch (IOException ioe) {
11963            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11964        } finally {
11965            IoUtils.closeQuietly(handle);
11966        }
11967
11968        // Now that we've calculated the ABIs and determined if it's an internal app,
11969        // we will go ahead and populate the nativeLibraryPath.
11970        setNativeLibraryPaths(pkg, appLib32InstallDir);
11971    }
11972
11973    /**
11974     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11975     * i.e, so that all packages can be run inside a single process if required.
11976     *
11977     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11978     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11979     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11980     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11981     * updating a package that belongs to a shared user.
11982     *
11983     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11984     * adds unnecessary complexity.
11985     */
11986    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11987            PackageParser.Package scannedPackage) {
11988        String requiredInstructionSet = null;
11989        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11990            requiredInstructionSet = VMRuntime.getInstructionSet(
11991                     scannedPackage.applicationInfo.primaryCpuAbi);
11992        }
11993
11994        PackageSetting requirer = null;
11995        for (PackageSetting ps : packagesForUser) {
11996            // If packagesForUser contains scannedPackage, we skip it. This will happen
11997            // when scannedPackage is an update of an existing package. Without this check,
11998            // we will never be able to change the ABI of any package belonging to a shared
11999            // user, even if it's compatible with other packages.
12000            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12001                if (ps.primaryCpuAbiString == null) {
12002                    continue;
12003                }
12004
12005                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
12006                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
12007                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
12008                    // this but there's not much we can do.
12009                    String errorMessage = "Instruction set mismatch, "
12010                            + ((requirer == null) ? "[caller]" : requirer)
12011                            + " requires " + requiredInstructionSet + " whereas " + ps
12012                            + " requires " + instructionSet;
12013                    Slog.w(TAG, errorMessage);
12014                }
12015
12016                if (requiredInstructionSet == null) {
12017                    requiredInstructionSet = instructionSet;
12018                    requirer = ps;
12019                }
12020            }
12021        }
12022
12023        if (requiredInstructionSet != null) {
12024            String adjustedAbi;
12025            if (requirer != null) {
12026                // requirer != null implies that either scannedPackage was null or that scannedPackage
12027                // did not require an ABI, in which case we have to adjust scannedPackage to match
12028                // the ABI of the set (which is the same as requirer's ABI)
12029                adjustedAbi = requirer.primaryCpuAbiString;
12030                if (scannedPackage != null) {
12031                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
12032                }
12033            } else {
12034                // requirer == null implies that we're updating all ABIs in the set to
12035                // match scannedPackage.
12036                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
12037            }
12038
12039            for (PackageSetting ps : packagesForUser) {
12040                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12041                    if (ps.primaryCpuAbiString != null) {
12042                        continue;
12043                    }
12044
12045                    ps.primaryCpuAbiString = adjustedAbi;
12046                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
12047                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
12048                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
12049                        if (DEBUG_ABI_SELECTION) {
12050                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
12051                                    + " (requirer="
12052                                    + (requirer != null ? requirer.pkg : "null")
12053                                    + ", scannedPackage="
12054                                    + (scannedPackage != null ? scannedPackage : "null")
12055                                    + ")");
12056                        }
12057                        try {
12058                            mInstaller.rmdex(ps.codePathString,
12059                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
12060                        } catch (InstallerException ignored) {
12061                        }
12062                    }
12063                }
12064            }
12065        }
12066    }
12067
12068    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
12069        synchronized (mPackages) {
12070            mResolverReplaced = true;
12071            // Set up information for custom user intent resolution activity.
12072            mResolveActivity.applicationInfo = pkg.applicationInfo;
12073            mResolveActivity.name = mCustomResolverComponentName.getClassName();
12074            mResolveActivity.packageName = pkg.applicationInfo.packageName;
12075            mResolveActivity.processName = pkg.applicationInfo.packageName;
12076            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
12077            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
12078                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12079            mResolveActivity.theme = 0;
12080            mResolveActivity.exported = true;
12081            mResolveActivity.enabled = true;
12082            mResolveInfo.activityInfo = mResolveActivity;
12083            mResolveInfo.priority = 0;
12084            mResolveInfo.preferredOrder = 0;
12085            mResolveInfo.match = 0;
12086            mResolveComponentName = mCustomResolverComponentName;
12087            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
12088                    mResolveComponentName);
12089        }
12090    }
12091
12092    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
12093        if (installerActivity == null) {
12094            if (DEBUG_EPHEMERAL) {
12095                Slog.d(TAG, "Clear ephemeral installer activity");
12096            }
12097            mInstantAppInstallerActivity = null;
12098            return;
12099        }
12100
12101        if (DEBUG_EPHEMERAL) {
12102            Slog.d(TAG, "Set ephemeral installer activity: "
12103                    + installerActivity.getComponentName());
12104        }
12105        // Set up information for ephemeral installer activity
12106        mInstantAppInstallerActivity = installerActivity;
12107        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
12108                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12109        mInstantAppInstallerActivity.exported = true;
12110        mInstantAppInstallerActivity.enabled = true;
12111        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
12112        mInstantAppInstallerInfo.priority = 0;
12113        mInstantAppInstallerInfo.preferredOrder = 1;
12114        mInstantAppInstallerInfo.isDefault = true;
12115        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
12116                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
12117    }
12118
12119    private static String calculateBundledApkRoot(final String codePathString) {
12120        final File codePath = new File(codePathString);
12121        final File codeRoot;
12122        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
12123            codeRoot = Environment.getRootDirectory();
12124        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
12125            codeRoot = Environment.getOemDirectory();
12126        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
12127            codeRoot = Environment.getVendorDirectory();
12128        } else {
12129            // Unrecognized code path; take its top real segment as the apk root:
12130            // e.g. /something/app/blah.apk => /something
12131            try {
12132                File f = codePath.getCanonicalFile();
12133                File parent = f.getParentFile();    // non-null because codePath is a file
12134                File tmp;
12135                while ((tmp = parent.getParentFile()) != null) {
12136                    f = parent;
12137                    parent = tmp;
12138                }
12139                codeRoot = f;
12140                Slog.w(TAG, "Unrecognized code path "
12141                        + codePath + " - using " + codeRoot);
12142            } catch (IOException e) {
12143                // Can't canonicalize the code path -- shenanigans?
12144                Slog.w(TAG, "Can't canonicalize code path " + codePath);
12145                return Environment.getRootDirectory().getPath();
12146            }
12147        }
12148        return codeRoot.getPath();
12149    }
12150
12151    /**
12152     * Derive and set the location of native libraries for the given package,
12153     * which varies depending on where and how the package was installed.
12154     */
12155    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
12156        final ApplicationInfo info = pkg.applicationInfo;
12157        final String codePath = pkg.codePath;
12158        final File codeFile = new File(codePath);
12159        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
12160        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
12161
12162        info.nativeLibraryRootDir = null;
12163        info.nativeLibraryRootRequiresIsa = false;
12164        info.nativeLibraryDir = null;
12165        info.secondaryNativeLibraryDir = null;
12166
12167        if (isApkFile(codeFile)) {
12168            // Monolithic install
12169            if (bundledApp) {
12170                // If "/system/lib64/apkname" exists, assume that is the per-package
12171                // native library directory to use; otherwise use "/system/lib/apkname".
12172                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
12173                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
12174                        getPrimaryInstructionSet(info));
12175
12176                // This is a bundled system app so choose the path based on the ABI.
12177                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
12178                // is just the default path.
12179                final String apkName = deriveCodePathName(codePath);
12180                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
12181                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
12182                        apkName).getAbsolutePath();
12183
12184                if (info.secondaryCpuAbi != null) {
12185                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
12186                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
12187                            secondaryLibDir, apkName).getAbsolutePath();
12188                }
12189            } else if (asecApp) {
12190                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
12191                        .getAbsolutePath();
12192            } else {
12193                final String apkName = deriveCodePathName(codePath);
12194                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
12195                        .getAbsolutePath();
12196            }
12197
12198            info.nativeLibraryRootRequiresIsa = false;
12199            info.nativeLibraryDir = info.nativeLibraryRootDir;
12200        } else {
12201            // Cluster install
12202            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
12203            info.nativeLibraryRootRequiresIsa = true;
12204
12205            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
12206                    getPrimaryInstructionSet(info)).getAbsolutePath();
12207
12208            if (info.secondaryCpuAbi != null) {
12209                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
12210                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
12211            }
12212        }
12213    }
12214
12215    /**
12216     * Calculate the abis and roots for a bundled app. These can uniquely
12217     * be determined from the contents of the system partition, i.e whether
12218     * it contains 64 or 32 bit shared libraries etc. We do not validate any
12219     * of this information, and instead assume that the system was built
12220     * sensibly.
12221     */
12222    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
12223                                           PackageSetting pkgSetting) {
12224        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
12225
12226        // If "/system/lib64/apkname" exists, assume that is the per-package
12227        // native library directory to use; otherwise use "/system/lib/apkname".
12228        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
12229        setBundledAppAbi(pkg, apkRoot, apkName);
12230        // pkgSetting might be null during rescan following uninstall of updates
12231        // to a bundled app, so accommodate that possibility.  The settings in
12232        // that case will be established later from the parsed package.
12233        //
12234        // If the settings aren't null, sync them up with what we've just derived.
12235        // note that apkRoot isn't stored in the package settings.
12236        if (pkgSetting != null) {
12237            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
12238            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
12239        }
12240    }
12241
12242    /**
12243     * Deduces the ABI of a bundled app and sets the relevant fields on the
12244     * parsed pkg object.
12245     *
12246     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
12247     *        under which system libraries are installed.
12248     * @param apkName the name of the installed package.
12249     */
12250    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
12251        final File codeFile = new File(pkg.codePath);
12252
12253        final boolean has64BitLibs;
12254        final boolean has32BitLibs;
12255        if (isApkFile(codeFile)) {
12256            // Monolithic install
12257            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12258            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12259        } else {
12260            // Cluster install
12261            final File rootDir = new File(codeFile, LIB_DIR_NAME);
12262            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12263                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12264                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12265                has64BitLibs = (new File(rootDir, isa)).exists();
12266            } else {
12267                has64BitLibs = false;
12268            }
12269            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12270                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12271                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12272                has32BitLibs = (new File(rootDir, isa)).exists();
12273            } else {
12274                has32BitLibs = false;
12275            }
12276        }
12277
12278        if (has64BitLibs && !has32BitLibs) {
12279            // The package has 64 bit libs, but not 32 bit libs. Its primary
12280            // ABI should be 64 bit. We can safely assume here that the bundled
12281            // native libraries correspond to the most preferred ABI in the list.
12282
12283            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12284            pkg.applicationInfo.secondaryCpuAbi = null;
12285        } else if (has32BitLibs && !has64BitLibs) {
12286            // The package has 32 bit libs but not 64 bit libs. Its primary
12287            // ABI should be 32 bit.
12288
12289            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12290            pkg.applicationInfo.secondaryCpuAbi = null;
12291        } else if (has32BitLibs && has64BitLibs) {
12292            // The application has both 64 and 32 bit bundled libraries. We check
12293            // here that the app declares multiArch support, and warn if it doesn't.
12294            //
12295            // We will be lenient here and record both ABIs. The primary will be the
12296            // ABI that's higher on the list, i.e, a device that's configured to prefer
12297            // 64 bit apps will see a 64 bit primary ABI,
12298
12299            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12300                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12301            }
12302
12303            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12304                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12305                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12306            } else {
12307                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12308                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12309            }
12310        } else {
12311            pkg.applicationInfo.primaryCpuAbi = null;
12312            pkg.applicationInfo.secondaryCpuAbi = null;
12313        }
12314    }
12315
12316    private void killApplication(String pkgName, int appId, String reason) {
12317        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12318    }
12319
12320    private void killApplication(String pkgName, int appId, int userId, String reason) {
12321        // Request the ActivityManager to kill the process(only for existing packages)
12322        // so that we do not end up in a confused state while the user is still using the older
12323        // version of the application while the new one gets installed.
12324        final long token = Binder.clearCallingIdentity();
12325        try {
12326            IActivityManager am = ActivityManager.getService();
12327            if (am != null) {
12328                try {
12329                    am.killApplication(pkgName, appId, userId, reason);
12330                } catch (RemoteException e) {
12331                }
12332            }
12333        } finally {
12334            Binder.restoreCallingIdentity(token);
12335        }
12336    }
12337
12338    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12339        // Remove the parent package setting
12340        PackageSetting ps = (PackageSetting) pkg.mExtras;
12341        if (ps != null) {
12342            removePackageLI(ps, chatty);
12343        }
12344        // Remove the child package setting
12345        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12346        for (int i = 0; i < childCount; i++) {
12347            PackageParser.Package childPkg = pkg.childPackages.get(i);
12348            ps = (PackageSetting) childPkg.mExtras;
12349            if (ps != null) {
12350                removePackageLI(ps, chatty);
12351            }
12352        }
12353    }
12354
12355    void removePackageLI(PackageSetting ps, boolean chatty) {
12356        if (DEBUG_INSTALL) {
12357            if (chatty)
12358                Log.d(TAG, "Removing package " + ps.name);
12359        }
12360
12361        // writer
12362        synchronized (mPackages) {
12363            mPackages.remove(ps.name);
12364            final PackageParser.Package pkg = ps.pkg;
12365            if (pkg != null) {
12366                cleanPackageDataStructuresLILPw(pkg, chatty);
12367            }
12368        }
12369    }
12370
12371    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12372        if (DEBUG_INSTALL) {
12373            if (chatty)
12374                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12375        }
12376
12377        // writer
12378        synchronized (mPackages) {
12379            // Remove the parent package
12380            mPackages.remove(pkg.applicationInfo.packageName);
12381            cleanPackageDataStructuresLILPw(pkg, chatty);
12382
12383            // Remove the child packages
12384            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12385            for (int i = 0; i < childCount; i++) {
12386                PackageParser.Package childPkg = pkg.childPackages.get(i);
12387                mPackages.remove(childPkg.applicationInfo.packageName);
12388                cleanPackageDataStructuresLILPw(childPkg, chatty);
12389            }
12390        }
12391    }
12392
12393    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12394        int N = pkg.providers.size();
12395        StringBuilder r = null;
12396        int i;
12397        for (i=0; i<N; i++) {
12398            PackageParser.Provider p = pkg.providers.get(i);
12399            mProviders.removeProvider(p);
12400            if (p.info.authority == null) {
12401
12402                /* There was another ContentProvider with this authority when
12403                 * this app was installed so this authority is null,
12404                 * Ignore it as we don't have to unregister the provider.
12405                 */
12406                continue;
12407            }
12408            String names[] = p.info.authority.split(";");
12409            for (int j = 0; j < names.length; j++) {
12410                if (mProvidersByAuthority.get(names[j]) == p) {
12411                    mProvidersByAuthority.remove(names[j]);
12412                    if (DEBUG_REMOVE) {
12413                        if (chatty)
12414                            Log.d(TAG, "Unregistered content provider: " + names[j]
12415                                    + ", className = " + p.info.name + ", isSyncable = "
12416                                    + p.info.isSyncable);
12417                    }
12418                }
12419            }
12420            if (DEBUG_REMOVE && chatty) {
12421                if (r == null) {
12422                    r = new StringBuilder(256);
12423                } else {
12424                    r.append(' ');
12425                }
12426                r.append(p.info.name);
12427            }
12428        }
12429        if (r != null) {
12430            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12431        }
12432
12433        N = pkg.services.size();
12434        r = null;
12435        for (i=0; i<N; i++) {
12436            PackageParser.Service s = pkg.services.get(i);
12437            mServices.removeService(s);
12438            if (chatty) {
12439                if (r == null) {
12440                    r = new StringBuilder(256);
12441                } else {
12442                    r.append(' ');
12443                }
12444                r.append(s.info.name);
12445            }
12446        }
12447        if (r != null) {
12448            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12449        }
12450
12451        N = pkg.receivers.size();
12452        r = null;
12453        for (i=0; i<N; i++) {
12454            PackageParser.Activity a = pkg.receivers.get(i);
12455            mReceivers.removeActivity(a, "receiver");
12456            if (DEBUG_REMOVE && chatty) {
12457                if (r == null) {
12458                    r = new StringBuilder(256);
12459                } else {
12460                    r.append(' ');
12461                }
12462                r.append(a.info.name);
12463            }
12464        }
12465        if (r != null) {
12466            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12467        }
12468
12469        N = pkg.activities.size();
12470        r = null;
12471        for (i=0; i<N; i++) {
12472            PackageParser.Activity a = pkg.activities.get(i);
12473            mActivities.removeActivity(a, "activity");
12474            if (DEBUG_REMOVE && chatty) {
12475                if (r == null) {
12476                    r = new StringBuilder(256);
12477                } else {
12478                    r.append(' ');
12479                }
12480                r.append(a.info.name);
12481            }
12482        }
12483        if (r != null) {
12484            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12485        }
12486
12487        N = pkg.permissions.size();
12488        r = null;
12489        for (i=0; i<N; i++) {
12490            PackageParser.Permission p = pkg.permissions.get(i);
12491            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12492            if (bp == null) {
12493                bp = mSettings.mPermissionTrees.get(p.info.name);
12494            }
12495            if (bp != null && bp.perm == p) {
12496                bp.perm = null;
12497                if (DEBUG_REMOVE && chatty) {
12498                    if (r == null) {
12499                        r = new StringBuilder(256);
12500                    } else {
12501                        r.append(' ');
12502                    }
12503                    r.append(p.info.name);
12504                }
12505            }
12506            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12507                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12508                if (appOpPkgs != null) {
12509                    appOpPkgs.remove(pkg.packageName);
12510                }
12511            }
12512        }
12513        if (r != null) {
12514            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12515        }
12516
12517        N = pkg.requestedPermissions.size();
12518        r = null;
12519        for (i=0; i<N; i++) {
12520            String perm = pkg.requestedPermissions.get(i);
12521            BasePermission bp = mSettings.mPermissions.get(perm);
12522            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12523                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12524                if (appOpPkgs != null) {
12525                    appOpPkgs.remove(pkg.packageName);
12526                    if (appOpPkgs.isEmpty()) {
12527                        mAppOpPermissionPackages.remove(perm);
12528                    }
12529                }
12530            }
12531        }
12532        if (r != null) {
12533            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12534        }
12535
12536        N = pkg.instrumentation.size();
12537        r = null;
12538        for (i=0; i<N; i++) {
12539            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12540            mInstrumentation.remove(a.getComponentName());
12541            if (DEBUG_REMOVE && chatty) {
12542                if (r == null) {
12543                    r = new StringBuilder(256);
12544                } else {
12545                    r.append(' ');
12546                }
12547                r.append(a.info.name);
12548            }
12549        }
12550        if (r != null) {
12551            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12552        }
12553
12554        r = null;
12555        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12556            // Only system apps can hold shared libraries.
12557            if (pkg.libraryNames != null) {
12558                for (i = 0; i < pkg.libraryNames.size(); i++) {
12559                    String name = pkg.libraryNames.get(i);
12560                    if (removeSharedLibraryLPw(name, 0)) {
12561                        if (DEBUG_REMOVE && chatty) {
12562                            if (r == null) {
12563                                r = new StringBuilder(256);
12564                            } else {
12565                                r.append(' ');
12566                            }
12567                            r.append(name);
12568                        }
12569                    }
12570                }
12571            }
12572        }
12573
12574        r = null;
12575
12576        // Any package can hold static shared libraries.
12577        if (pkg.staticSharedLibName != null) {
12578            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12579                if (DEBUG_REMOVE && chatty) {
12580                    if (r == null) {
12581                        r = new StringBuilder(256);
12582                    } else {
12583                        r.append(' ');
12584                    }
12585                    r.append(pkg.staticSharedLibName);
12586                }
12587            }
12588        }
12589
12590        if (r != null) {
12591            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12592        }
12593    }
12594
12595    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12596        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12597            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12598                return true;
12599            }
12600        }
12601        return false;
12602    }
12603
12604    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12605    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12606    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12607
12608    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12609        // Update the parent permissions
12610        updatePermissionsLPw(pkg.packageName, pkg, flags);
12611        // Update the child permissions
12612        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12613        for (int i = 0; i < childCount; i++) {
12614            PackageParser.Package childPkg = pkg.childPackages.get(i);
12615            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12616        }
12617    }
12618
12619    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12620            int flags) {
12621        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12622        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12623    }
12624
12625    private void updatePermissionsLPw(String changingPkg,
12626            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12627        // Make sure there are no dangling permission trees.
12628        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12629        while (it.hasNext()) {
12630            final BasePermission bp = it.next();
12631            if (bp.packageSetting == null) {
12632                // We may not yet have parsed the package, so just see if
12633                // we still know about its settings.
12634                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12635            }
12636            if (bp.packageSetting == null) {
12637                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12638                        + " from package " + bp.sourcePackage);
12639                it.remove();
12640            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12641                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12642                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12643                            + " from package " + bp.sourcePackage);
12644                    flags |= UPDATE_PERMISSIONS_ALL;
12645                    it.remove();
12646                }
12647            }
12648        }
12649
12650        // Make sure all dynamic permissions have been assigned to a package,
12651        // and make sure there are no dangling permissions.
12652        it = mSettings.mPermissions.values().iterator();
12653        while (it.hasNext()) {
12654            final BasePermission bp = it.next();
12655            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12656                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12657                        + bp.name + " pkg=" + bp.sourcePackage
12658                        + " info=" + bp.pendingInfo);
12659                if (bp.packageSetting == null && bp.pendingInfo != null) {
12660                    final BasePermission tree = findPermissionTreeLP(bp.name);
12661                    if (tree != null && tree.perm != null) {
12662                        bp.packageSetting = tree.packageSetting;
12663                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12664                                new PermissionInfo(bp.pendingInfo));
12665                        bp.perm.info.packageName = tree.perm.info.packageName;
12666                        bp.perm.info.name = bp.name;
12667                        bp.uid = tree.uid;
12668                    }
12669                }
12670            }
12671            if (bp.packageSetting == null) {
12672                // We may not yet have parsed the package, so just see if
12673                // we still know about its settings.
12674                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12675            }
12676            if (bp.packageSetting == null) {
12677                Slog.w(TAG, "Removing dangling permission: " + bp.name
12678                        + " from package " + bp.sourcePackage);
12679                it.remove();
12680            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12681                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12682                    Slog.i(TAG, "Removing old permission: " + bp.name
12683                            + " from package " + bp.sourcePackage);
12684                    flags |= UPDATE_PERMISSIONS_ALL;
12685                    it.remove();
12686                }
12687            }
12688        }
12689
12690        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12691        // Now update the permissions for all packages, in particular
12692        // replace the granted permissions of the system packages.
12693        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12694            for (PackageParser.Package pkg : mPackages.values()) {
12695                if (pkg != pkgInfo) {
12696                    // Only replace for packages on requested volume
12697                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12698                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12699                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12700                    grantPermissionsLPw(pkg, replace, changingPkg);
12701                }
12702            }
12703        }
12704
12705        if (pkgInfo != null) {
12706            // Only replace for packages on requested volume
12707            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12708            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12709                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12710            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12711        }
12712        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12713    }
12714
12715    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12716            String packageOfInterest) {
12717        // IMPORTANT: There are two types of permissions: install and runtime.
12718        // Install time permissions are granted when the app is installed to
12719        // all device users and users added in the future. Runtime permissions
12720        // are granted at runtime explicitly to specific users. Normal and signature
12721        // protected permissions are install time permissions. Dangerous permissions
12722        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12723        // otherwise they are runtime permissions. This function does not manage
12724        // runtime permissions except for the case an app targeting Lollipop MR1
12725        // being upgraded to target a newer SDK, in which case dangerous permissions
12726        // are transformed from install time to runtime ones.
12727
12728        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12729        if (ps == null) {
12730            return;
12731        }
12732
12733        PermissionsState permissionsState = ps.getPermissionsState();
12734        PermissionsState origPermissions = permissionsState;
12735
12736        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12737
12738        boolean runtimePermissionsRevoked = false;
12739        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12740
12741        boolean changedInstallPermission = false;
12742
12743        if (replace) {
12744            ps.installPermissionsFixed = false;
12745            if (!ps.isSharedUser()) {
12746                origPermissions = new PermissionsState(permissionsState);
12747                permissionsState.reset();
12748            } else {
12749                // We need to know only about runtime permission changes since the
12750                // calling code always writes the install permissions state but
12751                // the runtime ones are written only if changed. The only cases of
12752                // changed runtime permissions here are promotion of an install to
12753                // runtime and revocation of a runtime from a shared user.
12754                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12755                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12756                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12757                    runtimePermissionsRevoked = true;
12758                }
12759            }
12760        }
12761
12762        permissionsState.setGlobalGids(mGlobalGids);
12763
12764        final int N = pkg.requestedPermissions.size();
12765        for (int i=0; i<N; i++) {
12766            final String name = pkg.requestedPermissions.get(i);
12767            final BasePermission bp = mSettings.mPermissions.get(name);
12768            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12769                    >= Build.VERSION_CODES.M;
12770
12771            if (DEBUG_INSTALL) {
12772                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12773            }
12774
12775            if (bp == null || bp.packageSetting == null) {
12776                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12777                    if (DEBUG_PERMISSIONS) {
12778                        Slog.i(TAG, "Unknown permission " + name
12779                                + " in package " + pkg.packageName);
12780                    }
12781                }
12782                continue;
12783            }
12784
12785
12786            // Limit ephemeral apps to ephemeral allowed permissions.
12787            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12788                if (DEBUG_PERMISSIONS) {
12789                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12790                            + pkg.packageName);
12791                }
12792                continue;
12793            }
12794
12795            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12796                if (DEBUG_PERMISSIONS) {
12797                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12798                            + pkg.packageName);
12799                }
12800                continue;
12801            }
12802
12803            final String perm = bp.name;
12804            boolean allowedSig = false;
12805            int grant = GRANT_DENIED;
12806
12807            // Keep track of app op permissions.
12808            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12809                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12810                if (pkgs == null) {
12811                    pkgs = new ArraySet<>();
12812                    mAppOpPermissionPackages.put(bp.name, pkgs);
12813                }
12814                pkgs.add(pkg.packageName);
12815            }
12816
12817            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12818            switch (level) {
12819                case PermissionInfo.PROTECTION_NORMAL: {
12820                    // For all apps normal permissions are install time ones.
12821                    grant = GRANT_INSTALL;
12822                } break;
12823
12824                case PermissionInfo.PROTECTION_DANGEROUS: {
12825                    // If a permission review is required for legacy apps we represent
12826                    // their permissions as always granted runtime ones since we need
12827                    // to keep the review required permission flag per user while an
12828                    // install permission's state is shared across all users.
12829                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12830                        // For legacy apps dangerous permissions are install time ones.
12831                        grant = GRANT_INSTALL;
12832                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12833                        // For legacy apps that became modern, install becomes runtime.
12834                        grant = GRANT_UPGRADE;
12835                    } else if (mPromoteSystemApps
12836                            && isSystemApp(ps)
12837                            && mExistingSystemPackages.contains(ps.name)) {
12838                        // For legacy system apps, install becomes runtime.
12839                        // We cannot check hasInstallPermission() for system apps since those
12840                        // permissions were granted implicitly and not persisted pre-M.
12841                        grant = GRANT_UPGRADE;
12842                    } else {
12843                        // For modern apps keep runtime permissions unchanged.
12844                        grant = GRANT_RUNTIME;
12845                    }
12846                } break;
12847
12848                case PermissionInfo.PROTECTION_SIGNATURE: {
12849                    // For all apps signature permissions are install time ones.
12850                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12851                    if (allowedSig) {
12852                        grant = GRANT_INSTALL;
12853                    }
12854                } break;
12855            }
12856
12857            if (DEBUG_PERMISSIONS) {
12858                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12859            }
12860
12861            if (grant != GRANT_DENIED) {
12862                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12863                    // If this is an existing, non-system package, then
12864                    // we can't add any new permissions to it.
12865                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12866                        // Except...  if this is a permission that was added
12867                        // to the platform (note: need to only do this when
12868                        // updating the platform).
12869                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12870                            grant = GRANT_DENIED;
12871                        }
12872                    }
12873                }
12874
12875                switch (grant) {
12876                    case GRANT_INSTALL: {
12877                        // Revoke this as runtime permission to handle the case of
12878                        // a runtime permission being downgraded to an install one.
12879                        // Also in permission review mode we keep dangerous permissions
12880                        // for legacy apps
12881                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12882                            if (origPermissions.getRuntimePermissionState(
12883                                    bp.name, userId) != null) {
12884                                // Revoke the runtime permission and clear the flags.
12885                                origPermissions.revokeRuntimePermission(bp, userId);
12886                                origPermissions.updatePermissionFlags(bp, userId,
12887                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12888                                // If we revoked a permission permission, we have to write.
12889                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12890                                        changedRuntimePermissionUserIds, userId);
12891                            }
12892                        }
12893                        // Grant an install permission.
12894                        if (permissionsState.grantInstallPermission(bp) !=
12895                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12896                            changedInstallPermission = true;
12897                        }
12898                    } break;
12899
12900                    case GRANT_RUNTIME: {
12901                        // Grant previously granted runtime permissions.
12902                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12903                            PermissionState permissionState = origPermissions
12904                                    .getRuntimePermissionState(bp.name, userId);
12905                            int flags = permissionState != null
12906                                    ? permissionState.getFlags() : 0;
12907                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12908                                // Don't propagate the permission in a permission review mode if
12909                                // the former was revoked, i.e. marked to not propagate on upgrade.
12910                                // Note that in a permission review mode install permissions are
12911                                // represented as constantly granted runtime ones since we need to
12912                                // keep a per user state associated with the permission. Also the
12913                                // revoke on upgrade flag is no longer applicable and is reset.
12914                                final boolean revokeOnUpgrade = (flags & PackageManager
12915                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12916                                if (revokeOnUpgrade) {
12917                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12918                                    // Since we changed the flags, we have to write.
12919                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12920                                            changedRuntimePermissionUserIds, userId);
12921                                }
12922                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12923                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12924                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12925                                        // If we cannot put the permission as it was,
12926                                        // we have to write.
12927                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12928                                                changedRuntimePermissionUserIds, userId);
12929                                    }
12930                                }
12931
12932                                // If the app supports runtime permissions no need for a review.
12933                                if (mPermissionReviewRequired
12934                                        && appSupportsRuntimePermissions
12935                                        && (flags & PackageManager
12936                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12937                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12938                                    // Since we changed the flags, we have to write.
12939                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12940                                            changedRuntimePermissionUserIds, userId);
12941                                }
12942                            } else if (mPermissionReviewRequired
12943                                    && !appSupportsRuntimePermissions) {
12944                                // For legacy apps that need a permission review, every new
12945                                // runtime permission is granted but it is pending a review.
12946                                // We also need to review only platform defined runtime
12947                                // permissions as these are the only ones the platform knows
12948                                // how to disable the API to simulate revocation as legacy
12949                                // apps don't expect to run with revoked permissions.
12950                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12951                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12952                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12953                                        // We changed the flags, hence have to write.
12954                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12955                                                changedRuntimePermissionUserIds, userId);
12956                                    }
12957                                }
12958                                if (permissionsState.grantRuntimePermission(bp, userId)
12959                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12960                                    // We changed the permission, hence have to write.
12961                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12962                                            changedRuntimePermissionUserIds, userId);
12963                                }
12964                            }
12965                            // Propagate the permission flags.
12966                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12967                        }
12968                    } break;
12969
12970                    case GRANT_UPGRADE: {
12971                        // Grant runtime permissions for a previously held install permission.
12972                        PermissionState permissionState = origPermissions
12973                                .getInstallPermissionState(bp.name);
12974                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12975
12976                        if (origPermissions.revokeInstallPermission(bp)
12977                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12978                            // We will be transferring the permission flags, so clear them.
12979                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12980                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12981                            changedInstallPermission = true;
12982                        }
12983
12984                        // If the permission is not to be promoted to runtime we ignore it and
12985                        // also its other flags as they are not applicable to install permissions.
12986                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12987                            for (int userId : currentUserIds) {
12988                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12989                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12990                                    // Transfer the permission flags.
12991                                    permissionsState.updatePermissionFlags(bp, userId,
12992                                            flags, flags);
12993                                    // If we granted the permission, we have to write.
12994                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12995                                            changedRuntimePermissionUserIds, userId);
12996                                }
12997                            }
12998                        }
12999                    } break;
13000
13001                    default: {
13002                        if (packageOfInterest == null
13003                                || packageOfInterest.equals(pkg.packageName)) {
13004                            if (DEBUG_PERMISSIONS) {
13005                                Slog.i(TAG, "Not granting permission " + perm
13006                                        + " to package " + pkg.packageName
13007                                        + " because it was previously installed without");
13008                            }
13009                        }
13010                    } break;
13011                }
13012            } else {
13013                if (permissionsState.revokeInstallPermission(bp) !=
13014                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
13015                    // Also drop the permission flags.
13016                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13017                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13018                    changedInstallPermission = true;
13019                    Slog.i(TAG, "Un-granting permission " + perm
13020                            + " from package " + pkg.packageName
13021                            + " (protectionLevel=" + bp.protectionLevel
13022                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13023                            + ")");
13024                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
13025                    // Don't print warning for app op permissions, since it is fine for them
13026                    // not to be granted, there is a UI for the user to decide.
13027                    if (DEBUG_PERMISSIONS
13028                            && (packageOfInterest == null
13029                                    || packageOfInterest.equals(pkg.packageName))) {
13030                        Slog.i(TAG, "Not granting permission " + perm
13031                                + " to package " + pkg.packageName
13032                                + " (protectionLevel=" + bp.protectionLevel
13033                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
13034                                + ")");
13035                    }
13036                }
13037            }
13038        }
13039
13040        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
13041                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
13042            // This is the first that we have heard about this package, so the
13043            // permissions we have now selected are fixed until explicitly
13044            // changed.
13045            ps.installPermissionsFixed = true;
13046        }
13047
13048        // Persist the runtime permissions state for users with changes. If permissions
13049        // were revoked because no app in the shared user declares them we have to
13050        // write synchronously to avoid losing runtime permissions state.
13051        for (int userId : changedRuntimePermissionUserIds) {
13052            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
13053        }
13054    }
13055
13056    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
13057        boolean allowed = false;
13058        final int NP = PackageParser.NEW_PERMISSIONS.length;
13059        for (int ip=0; ip<NP; ip++) {
13060            final PackageParser.NewPermissionInfo npi
13061                    = PackageParser.NEW_PERMISSIONS[ip];
13062            if (npi.name.equals(perm)
13063                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
13064                allowed = true;
13065                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
13066                        + pkg.packageName);
13067                break;
13068            }
13069        }
13070        return allowed;
13071    }
13072
13073    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
13074            BasePermission bp, PermissionsState origPermissions) {
13075        boolean privilegedPermission = (bp.protectionLevel
13076                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
13077        boolean privappPermissionsDisable =
13078                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
13079        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
13080        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
13081        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
13082                && !platformPackage && platformPermission) {
13083            ArraySet<String> wlPermissions = SystemConfig.getInstance()
13084                    .getPrivAppPermissions(pkg.packageName);
13085            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
13086            if (!whitelisted) {
13087                Slog.w(TAG, "Privileged permission " + perm + " for package "
13088                        + pkg.packageName + " - not in privapp-permissions whitelist");
13089                // Only report violations for apps on system image
13090                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
13091                    if (mPrivappPermissionsViolations == null) {
13092                        mPrivappPermissionsViolations = new ArraySet<>();
13093                    }
13094                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
13095                }
13096                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
13097                    return false;
13098                }
13099            }
13100        }
13101        boolean allowed = (compareSignatures(
13102                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
13103                        == PackageManager.SIGNATURE_MATCH)
13104                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
13105                        == PackageManager.SIGNATURE_MATCH);
13106        if (!allowed && privilegedPermission) {
13107            if (isSystemApp(pkg)) {
13108                // For updated system applications, a system permission
13109                // is granted only if it had been defined by the original application.
13110                if (pkg.isUpdatedSystemApp()) {
13111                    final PackageSetting sysPs = mSettings
13112                            .getDisabledSystemPkgLPr(pkg.packageName);
13113                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
13114                        // If the original was granted this permission, we take
13115                        // that grant decision as read and propagate it to the
13116                        // update.
13117                        if (sysPs.isPrivileged()) {
13118                            allowed = true;
13119                        }
13120                    } else {
13121                        // The system apk may have been updated with an older
13122                        // version of the one on the data partition, but which
13123                        // granted a new system permission that it didn't have
13124                        // before.  In this case we do want to allow the app to
13125                        // now get the new permission if the ancestral apk is
13126                        // privileged to get it.
13127                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
13128                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
13129                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
13130                                    allowed = true;
13131                                    break;
13132                                }
13133                            }
13134                        }
13135                        // Also if a privileged parent package on the system image or any of
13136                        // its children requested a privileged permission, the updated child
13137                        // packages can also get the permission.
13138                        if (pkg.parentPackage != null) {
13139                            final PackageSetting disabledSysParentPs = mSettings
13140                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
13141                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
13142                                    && disabledSysParentPs.isPrivileged()) {
13143                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
13144                                    allowed = true;
13145                                } else if (disabledSysParentPs.pkg.childPackages != null) {
13146                                    final int count = disabledSysParentPs.pkg.childPackages.size();
13147                                    for (int i = 0; i < count; i++) {
13148                                        PackageParser.Package disabledSysChildPkg =
13149                                                disabledSysParentPs.pkg.childPackages.get(i);
13150                                        if (isPackageRequestingPermission(disabledSysChildPkg,
13151                                                perm)) {
13152                                            allowed = true;
13153                                            break;
13154                                        }
13155                                    }
13156                                }
13157                            }
13158                        }
13159                    }
13160                } else {
13161                    allowed = isPrivilegedApp(pkg);
13162                }
13163            }
13164        }
13165        if (!allowed) {
13166            if (!allowed && (bp.protectionLevel
13167                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
13168                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
13169                // If this was a previously normal/dangerous permission that got moved
13170                // to a system permission as part of the runtime permission redesign, then
13171                // we still want to blindly grant it to old apps.
13172                allowed = true;
13173            }
13174            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
13175                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
13176                // If this permission is to be granted to the system installer and
13177                // this app is an installer, then it gets the permission.
13178                allowed = true;
13179            }
13180            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
13181                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
13182                // If this permission is to be granted to the system verifier and
13183                // this app is a verifier, then it gets the permission.
13184                allowed = true;
13185            }
13186            if (!allowed && (bp.protectionLevel
13187                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
13188                    && isSystemApp(pkg)) {
13189                // Any pre-installed system app is allowed to get this permission.
13190                allowed = true;
13191            }
13192            if (!allowed && (bp.protectionLevel
13193                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
13194                // For development permissions, a development permission
13195                // is granted only if it was already granted.
13196                allowed = origPermissions.hasInstallPermission(perm);
13197            }
13198            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
13199                    && pkg.packageName.equals(mSetupWizardPackage)) {
13200                // If this permission is to be granted to the system setup wizard and
13201                // this app is a setup wizard, then it gets the permission.
13202                allowed = true;
13203            }
13204        }
13205        return allowed;
13206    }
13207
13208    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
13209        final int permCount = pkg.requestedPermissions.size();
13210        for (int j = 0; j < permCount; j++) {
13211            String requestedPermission = pkg.requestedPermissions.get(j);
13212            if (permission.equals(requestedPermission)) {
13213                return true;
13214            }
13215        }
13216        return false;
13217    }
13218
13219    final class ActivityIntentResolver
13220            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
13221        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13222                boolean defaultOnly, int userId) {
13223            if (!sUserManager.exists(userId)) return null;
13224            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
13225            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13226        }
13227
13228        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13229                int userId) {
13230            if (!sUserManager.exists(userId)) return null;
13231            mFlags = flags;
13232            return super.queryIntent(intent, resolvedType,
13233                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13234                    userId);
13235        }
13236
13237        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13238                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
13239            if (!sUserManager.exists(userId)) return null;
13240            if (packageActivities == null) {
13241                return null;
13242            }
13243            mFlags = flags;
13244            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13245            final int N = packageActivities.size();
13246            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
13247                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
13248
13249            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
13250            for (int i = 0; i < N; ++i) {
13251                intentFilters = packageActivities.get(i).intents;
13252                if (intentFilters != null && intentFilters.size() > 0) {
13253                    PackageParser.ActivityIntentInfo[] array =
13254                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
13255                    intentFilters.toArray(array);
13256                    listCut.add(array);
13257                }
13258            }
13259            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13260        }
13261
13262        /**
13263         * Finds a privileged activity that matches the specified activity names.
13264         */
13265        private PackageParser.Activity findMatchingActivity(
13266                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
13267            for (PackageParser.Activity sysActivity : activityList) {
13268                if (sysActivity.info.name.equals(activityInfo.name)) {
13269                    return sysActivity;
13270                }
13271                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
13272                    return sysActivity;
13273                }
13274                if (sysActivity.info.targetActivity != null) {
13275                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
13276                        return sysActivity;
13277                    }
13278                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
13279                        return sysActivity;
13280                    }
13281                }
13282            }
13283            return null;
13284        }
13285
13286        public class IterGenerator<E> {
13287            public Iterator<E> generate(ActivityIntentInfo info) {
13288                return null;
13289            }
13290        }
13291
13292        public class ActionIterGenerator extends IterGenerator<String> {
13293            @Override
13294            public Iterator<String> generate(ActivityIntentInfo info) {
13295                return info.actionsIterator();
13296            }
13297        }
13298
13299        public class CategoriesIterGenerator extends IterGenerator<String> {
13300            @Override
13301            public Iterator<String> generate(ActivityIntentInfo info) {
13302                return info.categoriesIterator();
13303            }
13304        }
13305
13306        public class SchemesIterGenerator extends IterGenerator<String> {
13307            @Override
13308            public Iterator<String> generate(ActivityIntentInfo info) {
13309                return info.schemesIterator();
13310            }
13311        }
13312
13313        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13314            @Override
13315            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13316                return info.authoritiesIterator();
13317            }
13318        }
13319
13320        /**
13321         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13322         * MODIFIED. Do not pass in a list that should not be changed.
13323         */
13324        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13325                IterGenerator<T> generator, Iterator<T> searchIterator) {
13326            // loop through the set of actions; every one must be found in the intent filter
13327            while (searchIterator.hasNext()) {
13328                // we must have at least one filter in the list to consider a match
13329                if (intentList.size() == 0) {
13330                    break;
13331                }
13332
13333                final T searchAction = searchIterator.next();
13334
13335                // loop through the set of intent filters
13336                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13337                while (intentIter.hasNext()) {
13338                    final ActivityIntentInfo intentInfo = intentIter.next();
13339                    boolean selectionFound = false;
13340
13341                    // loop through the intent filter's selection criteria; at least one
13342                    // of them must match the searched criteria
13343                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13344                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13345                        final T intentSelection = intentSelectionIter.next();
13346                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13347                            selectionFound = true;
13348                            break;
13349                        }
13350                    }
13351
13352                    // the selection criteria wasn't found in this filter's set; this filter
13353                    // is not a potential match
13354                    if (!selectionFound) {
13355                        intentIter.remove();
13356                    }
13357                }
13358            }
13359        }
13360
13361        private boolean isProtectedAction(ActivityIntentInfo filter) {
13362            final Iterator<String> actionsIter = filter.actionsIterator();
13363            while (actionsIter != null && actionsIter.hasNext()) {
13364                final String filterAction = actionsIter.next();
13365                if (PROTECTED_ACTIONS.contains(filterAction)) {
13366                    return true;
13367                }
13368            }
13369            return false;
13370        }
13371
13372        /**
13373         * Adjusts the priority of the given intent filter according to policy.
13374         * <p>
13375         * <ul>
13376         * <li>The priority for non privileged applications is capped to '0'</li>
13377         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13378         * <li>The priority for unbundled updates to privileged applications is capped to the
13379         *      priority defined on the system partition</li>
13380         * </ul>
13381         * <p>
13382         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13383         * allowed to obtain any priority on any action.
13384         */
13385        private void adjustPriority(
13386                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13387            // nothing to do; priority is fine as-is
13388            if (intent.getPriority() <= 0) {
13389                return;
13390            }
13391
13392            final ActivityInfo activityInfo = intent.activity.info;
13393            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13394
13395            final boolean privilegedApp =
13396                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13397            if (!privilegedApp) {
13398                // non-privileged applications can never define a priority >0
13399                if (DEBUG_FILTERS) {
13400                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13401                            + " package: " + applicationInfo.packageName
13402                            + " activity: " + intent.activity.className
13403                            + " origPrio: " + intent.getPriority());
13404                }
13405                intent.setPriority(0);
13406                return;
13407            }
13408
13409            if (systemActivities == null) {
13410                // the system package is not disabled; we're parsing the system partition
13411                if (isProtectedAction(intent)) {
13412                    if (mDeferProtectedFilters) {
13413                        // We can't deal with these just yet. No component should ever obtain a
13414                        // >0 priority for a protected actions, with ONE exception -- the setup
13415                        // wizard. The setup wizard, however, cannot be known until we're able to
13416                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13417                        // until all intent filters have been processed. Chicken, meet egg.
13418                        // Let the filter temporarily have a high priority and rectify the
13419                        // priorities after all system packages have been scanned.
13420                        mProtectedFilters.add(intent);
13421                        if (DEBUG_FILTERS) {
13422                            Slog.i(TAG, "Protected action; save for later;"
13423                                    + " package: " + applicationInfo.packageName
13424                                    + " activity: " + intent.activity.className
13425                                    + " origPrio: " + intent.getPriority());
13426                        }
13427                        return;
13428                    } else {
13429                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13430                            Slog.i(TAG, "No setup wizard;"
13431                                + " All protected intents capped to priority 0");
13432                        }
13433                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13434                            if (DEBUG_FILTERS) {
13435                                Slog.i(TAG, "Found setup wizard;"
13436                                    + " allow priority " + intent.getPriority() + ";"
13437                                    + " package: " + intent.activity.info.packageName
13438                                    + " activity: " + intent.activity.className
13439                                    + " priority: " + intent.getPriority());
13440                            }
13441                            // setup wizard gets whatever it wants
13442                            return;
13443                        }
13444                        if (DEBUG_FILTERS) {
13445                            Slog.i(TAG, "Protected action; cap priority to 0;"
13446                                    + " package: " + intent.activity.info.packageName
13447                                    + " activity: " + intent.activity.className
13448                                    + " origPrio: " + intent.getPriority());
13449                        }
13450                        intent.setPriority(0);
13451                        return;
13452                    }
13453                }
13454                // privileged apps on the system image get whatever priority they request
13455                return;
13456            }
13457
13458            // privileged app unbundled update ... try to find the same activity
13459            final PackageParser.Activity foundActivity =
13460                    findMatchingActivity(systemActivities, activityInfo);
13461            if (foundActivity == null) {
13462                // this is a new activity; it cannot obtain >0 priority
13463                if (DEBUG_FILTERS) {
13464                    Slog.i(TAG, "New activity; cap priority to 0;"
13465                            + " package: " + applicationInfo.packageName
13466                            + " activity: " + intent.activity.className
13467                            + " origPrio: " + intent.getPriority());
13468                }
13469                intent.setPriority(0);
13470                return;
13471            }
13472
13473            // found activity, now check for filter equivalence
13474
13475            // a shallow copy is enough; we modify the list, not its contents
13476            final List<ActivityIntentInfo> intentListCopy =
13477                    new ArrayList<>(foundActivity.intents);
13478            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13479
13480            // find matching action subsets
13481            final Iterator<String> actionsIterator = intent.actionsIterator();
13482            if (actionsIterator != null) {
13483                getIntentListSubset(
13484                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13485                if (intentListCopy.size() == 0) {
13486                    // no more intents to match; we're not equivalent
13487                    if (DEBUG_FILTERS) {
13488                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13489                                + " package: " + applicationInfo.packageName
13490                                + " activity: " + intent.activity.className
13491                                + " origPrio: " + intent.getPriority());
13492                    }
13493                    intent.setPriority(0);
13494                    return;
13495                }
13496            }
13497
13498            // find matching category subsets
13499            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13500            if (categoriesIterator != null) {
13501                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13502                        categoriesIterator);
13503                if (intentListCopy.size() == 0) {
13504                    // no more intents to match; we're not equivalent
13505                    if (DEBUG_FILTERS) {
13506                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13507                                + " package: " + applicationInfo.packageName
13508                                + " activity: " + intent.activity.className
13509                                + " origPrio: " + intent.getPriority());
13510                    }
13511                    intent.setPriority(0);
13512                    return;
13513                }
13514            }
13515
13516            // find matching schemes subsets
13517            final Iterator<String> schemesIterator = intent.schemesIterator();
13518            if (schemesIterator != null) {
13519                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13520                        schemesIterator);
13521                if (intentListCopy.size() == 0) {
13522                    // no more intents to match; we're not equivalent
13523                    if (DEBUG_FILTERS) {
13524                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13525                                + " package: " + applicationInfo.packageName
13526                                + " activity: " + intent.activity.className
13527                                + " origPrio: " + intent.getPriority());
13528                    }
13529                    intent.setPriority(0);
13530                    return;
13531                }
13532            }
13533
13534            // find matching authorities subsets
13535            final Iterator<IntentFilter.AuthorityEntry>
13536                    authoritiesIterator = intent.authoritiesIterator();
13537            if (authoritiesIterator != null) {
13538                getIntentListSubset(intentListCopy,
13539                        new AuthoritiesIterGenerator(),
13540                        authoritiesIterator);
13541                if (intentListCopy.size() == 0) {
13542                    // no more intents to match; we're not equivalent
13543                    if (DEBUG_FILTERS) {
13544                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13545                                + " package: " + applicationInfo.packageName
13546                                + " activity: " + intent.activity.className
13547                                + " origPrio: " + intent.getPriority());
13548                    }
13549                    intent.setPriority(0);
13550                    return;
13551                }
13552            }
13553
13554            // we found matching filter(s); app gets the max priority of all intents
13555            int cappedPriority = 0;
13556            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13557                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13558            }
13559            if (intent.getPriority() > cappedPriority) {
13560                if (DEBUG_FILTERS) {
13561                    Slog.i(TAG, "Found matching filter(s);"
13562                            + " cap priority to " + cappedPriority + ";"
13563                            + " package: " + applicationInfo.packageName
13564                            + " activity: " + intent.activity.className
13565                            + " origPrio: " + intent.getPriority());
13566                }
13567                intent.setPriority(cappedPriority);
13568                return;
13569            }
13570            // all this for nothing; the requested priority was <= what was on the system
13571        }
13572
13573        public final void addActivity(PackageParser.Activity a, String type) {
13574            mActivities.put(a.getComponentName(), a);
13575            if (DEBUG_SHOW_INFO)
13576                Log.v(
13577                TAG, "  " + type + " " +
13578                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13579            if (DEBUG_SHOW_INFO)
13580                Log.v(TAG, "    Class=" + a.info.name);
13581            final int NI = a.intents.size();
13582            for (int j=0; j<NI; j++) {
13583                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13584                if ("activity".equals(type)) {
13585                    final PackageSetting ps =
13586                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13587                    final List<PackageParser.Activity> systemActivities =
13588                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13589                    adjustPriority(systemActivities, intent);
13590                }
13591                if (DEBUG_SHOW_INFO) {
13592                    Log.v(TAG, "    IntentFilter:");
13593                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13594                }
13595                if (!intent.debugCheck()) {
13596                    Log.w(TAG, "==> For Activity " + a.info.name);
13597                }
13598                addFilter(intent);
13599            }
13600        }
13601
13602        public final void removeActivity(PackageParser.Activity a, String type) {
13603            mActivities.remove(a.getComponentName());
13604            if (DEBUG_SHOW_INFO) {
13605                Log.v(TAG, "  " + type + " "
13606                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13607                                : a.info.name) + ":");
13608                Log.v(TAG, "    Class=" + a.info.name);
13609            }
13610            final int NI = a.intents.size();
13611            for (int j=0; j<NI; j++) {
13612                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13613                if (DEBUG_SHOW_INFO) {
13614                    Log.v(TAG, "    IntentFilter:");
13615                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13616                }
13617                removeFilter(intent);
13618            }
13619        }
13620
13621        @Override
13622        protected boolean allowFilterResult(
13623                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13624            ActivityInfo filterAi = filter.activity.info;
13625            for (int i=dest.size()-1; i>=0; i--) {
13626                ActivityInfo destAi = dest.get(i).activityInfo;
13627                if (destAi.name == filterAi.name
13628                        && destAi.packageName == filterAi.packageName) {
13629                    return false;
13630                }
13631            }
13632            return true;
13633        }
13634
13635        @Override
13636        protected ActivityIntentInfo[] newArray(int size) {
13637            return new ActivityIntentInfo[size];
13638        }
13639
13640        @Override
13641        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13642            if (!sUserManager.exists(userId)) return true;
13643            PackageParser.Package p = filter.activity.owner;
13644            if (p != null) {
13645                PackageSetting ps = (PackageSetting)p.mExtras;
13646                if (ps != null) {
13647                    // System apps are never considered stopped for purposes of
13648                    // filtering, because there may be no way for the user to
13649                    // actually re-launch them.
13650                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13651                            && ps.getStopped(userId);
13652                }
13653            }
13654            return false;
13655        }
13656
13657        @Override
13658        protected boolean isPackageForFilter(String packageName,
13659                PackageParser.ActivityIntentInfo info) {
13660            return packageName.equals(info.activity.owner.packageName);
13661        }
13662
13663        @Override
13664        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13665                int match, int userId) {
13666            if (!sUserManager.exists(userId)) return null;
13667            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13668                return null;
13669            }
13670            final PackageParser.Activity activity = info.activity;
13671            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13672            if (ps == null) {
13673                return null;
13674            }
13675            final PackageUserState userState = ps.readUserState(userId);
13676            ActivityInfo ai =
13677                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
13678            if (ai == null) {
13679                return null;
13680            }
13681            final boolean matchExplicitlyVisibleOnly =
13682                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13683            final boolean matchVisibleToInstantApp =
13684                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13685            final boolean componentVisible =
13686                    matchVisibleToInstantApp
13687                    && info.isVisibleToInstantApp()
13688                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13689            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13690            // throw out filters that aren't visible to ephemeral apps
13691            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13692                return null;
13693            }
13694            // throw out instant app filters if we're not explicitly requesting them
13695            if (!matchInstantApp && userState.instantApp) {
13696                return null;
13697            }
13698            // throw out instant app filters if updates are available; will trigger
13699            // instant app resolution
13700            if (userState.instantApp && ps.isUpdateAvailable()) {
13701                return null;
13702            }
13703            final ResolveInfo res = new ResolveInfo();
13704            res.activityInfo = ai;
13705            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13706                res.filter = info;
13707            }
13708            if (info != null) {
13709                res.handleAllWebDataURI = info.handleAllWebDataURI();
13710            }
13711            res.priority = info.getPriority();
13712            res.preferredOrder = activity.owner.mPreferredOrder;
13713            //System.out.println("Result: " + res.activityInfo.className +
13714            //                   " = " + res.priority);
13715            res.match = match;
13716            res.isDefault = info.hasDefault;
13717            res.labelRes = info.labelRes;
13718            res.nonLocalizedLabel = info.nonLocalizedLabel;
13719            if (userNeedsBadging(userId)) {
13720                res.noResourceId = true;
13721            } else {
13722                res.icon = info.icon;
13723            }
13724            res.iconResourceId = info.icon;
13725            res.system = res.activityInfo.applicationInfo.isSystemApp();
13726            res.isInstantAppAvailable = userState.instantApp;
13727            return res;
13728        }
13729
13730        @Override
13731        protected void sortResults(List<ResolveInfo> results) {
13732            Collections.sort(results, mResolvePrioritySorter);
13733        }
13734
13735        @Override
13736        protected void dumpFilter(PrintWriter out, String prefix,
13737                PackageParser.ActivityIntentInfo filter) {
13738            out.print(prefix); out.print(
13739                    Integer.toHexString(System.identityHashCode(filter.activity)));
13740                    out.print(' ');
13741                    filter.activity.printComponentShortName(out);
13742                    out.print(" filter ");
13743                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13744        }
13745
13746        @Override
13747        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13748            return filter.activity;
13749        }
13750
13751        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13752            PackageParser.Activity activity = (PackageParser.Activity)label;
13753            out.print(prefix); out.print(
13754                    Integer.toHexString(System.identityHashCode(activity)));
13755                    out.print(' ');
13756                    activity.printComponentShortName(out);
13757            if (count > 1) {
13758                out.print(" ("); out.print(count); out.print(" filters)");
13759            }
13760            out.println();
13761        }
13762
13763        // Keys are String (activity class name), values are Activity.
13764        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13765                = new ArrayMap<ComponentName, PackageParser.Activity>();
13766        private int mFlags;
13767    }
13768
13769    private final class ServiceIntentResolver
13770            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13771        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13772                boolean defaultOnly, int userId) {
13773            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13774            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13775        }
13776
13777        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13778                int userId) {
13779            if (!sUserManager.exists(userId)) return null;
13780            mFlags = flags;
13781            return super.queryIntent(intent, resolvedType,
13782                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13783                    userId);
13784        }
13785
13786        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13787                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13788            if (!sUserManager.exists(userId)) return null;
13789            if (packageServices == null) {
13790                return null;
13791            }
13792            mFlags = flags;
13793            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13794            final int N = packageServices.size();
13795            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13796                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13797
13798            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13799            for (int i = 0; i < N; ++i) {
13800                intentFilters = packageServices.get(i).intents;
13801                if (intentFilters != null && intentFilters.size() > 0) {
13802                    PackageParser.ServiceIntentInfo[] array =
13803                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13804                    intentFilters.toArray(array);
13805                    listCut.add(array);
13806                }
13807            }
13808            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13809        }
13810
13811        public final void addService(PackageParser.Service s) {
13812            mServices.put(s.getComponentName(), s);
13813            if (DEBUG_SHOW_INFO) {
13814                Log.v(TAG, "  "
13815                        + (s.info.nonLocalizedLabel != null
13816                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13817                Log.v(TAG, "    Class=" + s.info.name);
13818            }
13819            final int NI = s.intents.size();
13820            int j;
13821            for (j=0; j<NI; j++) {
13822                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13823                if (DEBUG_SHOW_INFO) {
13824                    Log.v(TAG, "    IntentFilter:");
13825                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13826                }
13827                if (!intent.debugCheck()) {
13828                    Log.w(TAG, "==> For Service " + s.info.name);
13829                }
13830                addFilter(intent);
13831            }
13832        }
13833
13834        public final void removeService(PackageParser.Service s) {
13835            mServices.remove(s.getComponentName());
13836            if (DEBUG_SHOW_INFO) {
13837                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13838                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13839                Log.v(TAG, "    Class=" + s.info.name);
13840            }
13841            final int NI = s.intents.size();
13842            int j;
13843            for (j=0; j<NI; j++) {
13844                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13845                if (DEBUG_SHOW_INFO) {
13846                    Log.v(TAG, "    IntentFilter:");
13847                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13848                }
13849                removeFilter(intent);
13850            }
13851        }
13852
13853        @Override
13854        protected boolean allowFilterResult(
13855                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13856            ServiceInfo filterSi = filter.service.info;
13857            for (int i=dest.size()-1; i>=0; i--) {
13858                ServiceInfo destAi = dest.get(i).serviceInfo;
13859                if (destAi.name == filterSi.name
13860                        && destAi.packageName == filterSi.packageName) {
13861                    return false;
13862                }
13863            }
13864            return true;
13865        }
13866
13867        @Override
13868        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13869            return new PackageParser.ServiceIntentInfo[size];
13870        }
13871
13872        @Override
13873        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13874            if (!sUserManager.exists(userId)) return true;
13875            PackageParser.Package p = filter.service.owner;
13876            if (p != null) {
13877                PackageSetting ps = (PackageSetting)p.mExtras;
13878                if (ps != null) {
13879                    // System apps are never considered stopped for purposes of
13880                    // filtering, because there may be no way for the user to
13881                    // actually re-launch them.
13882                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13883                            && ps.getStopped(userId);
13884                }
13885            }
13886            return false;
13887        }
13888
13889        @Override
13890        protected boolean isPackageForFilter(String packageName,
13891                PackageParser.ServiceIntentInfo info) {
13892            return packageName.equals(info.service.owner.packageName);
13893        }
13894
13895        @Override
13896        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13897                int match, int userId) {
13898            if (!sUserManager.exists(userId)) return null;
13899            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13900            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13901                return null;
13902            }
13903            final PackageParser.Service service = info.service;
13904            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13905            if (ps == null) {
13906                return null;
13907            }
13908            final PackageUserState userState = ps.readUserState(userId);
13909            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13910                    userState, userId);
13911            if (si == null) {
13912                return null;
13913            }
13914            final boolean matchVisibleToInstantApp =
13915                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13916            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13917            // throw out filters that aren't visible to ephemeral apps
13918            if (matchVisibleToInstantApp
13919                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13920                return null;
13921            }
13922            // throw out ephemeral filters if we're not explicitly requesting them
13923            if (!isInstantApp && userState.instantApp) {
13924                return null;
13925            }
13926            // throw out instant app filters if updates are available; will trigger
13927            // instant app resolution
13928            if (userState.instantApp && ps.isUpdateAvailable()) {
13929                return null;
13930            }
13931            final ResolveInfo res = new ResolveInfo();
13932            res.serviceInfo = si;
13933            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13934                res.filter = filter;
13935            }
13936            res.priority = info.getPriority();
13937            res.preferredOrder = service.owner.mPreferredOrder;
13938            res.match = match;
13939            res.isDefault = info.hasDefault;
13940            res.labelRes = info.labelRes;
13941            res.nonLocalizedLabel = info.nonLocalizedLabel;
13942            res.icon = info.icon;
13943            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13944            return res;
13945        }
13946
13947        @Override
13948        protected void sortResults(List<ResolveInfo> results) {
13949            Collections.sort(results, mResolvePrioritySorter);
13950        }
13951
13952        @Override
13953        protected void dumpFilter(PrintWriter out, String prefix,
13954                PackageParser.ServiceIntentInfo filter) {
13955            out.print(prefix); out.print(
13956                    Integer.toHexString(System.identityHashCode(filter.service)));
13957                    out.print(' ');
13958                    filter.service.printComponentShortName(out);
13959                    out.print(" filter ");
13960                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13961        }
13962
13963        @Override
13964        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13965            return filter.service;
13966        }
13967
13968        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13969            PackageParser.Service service = (PackageParser.Service)label;
13970            out.print(prefix); out.print(
13971                    Integer.toHexString(System.identityHashCode(service)));
13972                    out.print(' ');
13973                    service.printComponentShortName(out);
13974            if (count > 1) {
13975                out.print(" ("); out.print(count); out.print(" filters)");
13976            }
13977            out.println();
13978        }
13979
13980//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13981//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13982//            final List<ResolveInfo> retList = Lists.newArrayList();
13983//            while (i.hasNext()) {
13984//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13985//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13986//                    retList.add(resolveInfo);
13987//                }
13988//            }
13989//            return retList;
13990//        }
13991
13992        // Keys are String (activity class name), values are Activity.
13993        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13994                = new ArrayMap<ComponentName, PackageParser.Service>();
13995        private int mFlags;
13996    }
13997
13998    private final class ProviderIntentResolver
13999            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
14000        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
14001                boolean defaultOnly, int userId) {
14002            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
14003            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
14004        }
14005
14006        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
14007                int userId) {
14008            if (!sUserManager.exists(userId))
14009                return null;
14010            mFlags = flags;
14011            return super.queryIntent(intent, resolvedType,
14012                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
14013                    userId);
14014        }
14015
14016        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
14017                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
14018            if (!sUserManager.exists(userId))
14019                return null;
14020            if (packageProviders == null) {
14021                return null;
14022            }
14023            mFlags = flags;
14024            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
14025            final int N = packageProviders.size();
14026            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
14027                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
14028
14029            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
14030            for (int i = 0; i < N; ++i) {
14031                intentFilters = packageProviders.get(i).intents;
14032                if (intentFilters != null && intentFilters.size() > 0) {
14033                    PackageParser.ProviderIntentInfo[] array =
14034                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
14035                    intentFilters.toArray(array);
14036                    listCut.add(array);
14037                }
14038            }
14039            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
14040        }
14041
14042        public final void addProvider(PackageParser.Provider p) {
14043            if (mProviders.containsKey(p.getComponentName())) {
14044                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
14045                return;
14046            }
14047
14048            mProviders.put(p.getComponentName(), p);
14049            if (DEBUG_SHOW_INFO) {
14050                Log.v(TAG, "  "
14051                        + (p.info.nonLocalizedLabel != null
14052                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
14053                Log.v(TAG, "    Class=" + p.info.name);
14054            }
14055            final int NI = p.intents.size();
14056            int j;
14057            for (j = 0; j < NI; j++) {
14058                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14059                if (DEBUG_SHOW_INFO) {
14060                    Log.v(TAG, "    IntentFilter:");
14061                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14062                }
14063                if (!intent.debugCheck()) {
14064                    Log.w(TAG, "==> For Provider " + p.info.name);
14065                }
14066                addFilter(intent);
14067            }
14068        }
14069
14070        public final void removeProvider(PackageParser.Provider p) {
14071            mProviders.remove(p.getComponentName());
14072            if (DEBUG_SHOW_INFO) {
14073                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
14074                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
14075                Log.v(TAG, "    Class=" + p.info.name);
14076            }
14077            final int NI = p.intents.size();
14078            int j;
14079            for (j = 0; j < NI; j++) {
14080                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
14081                if (DEBUG_SHOW_INFO) {
14082                    Log.v(TAG, "    IntentFilter:");
14083                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
14084                }
14085                removeFilter(intent);
14086            }
14087        }
14088
14089        @Override
14090        protected boolean allowFilterResult(
14091                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
14092            ProviderInfo filterPi = filter.provider.info;
14093            for (int i = dest.size() - 1; i >= 0; i--) {
14094                ProviderInfo destPi = dest.get(i).providerInfo;
14095                if (destPi.name == filterPi.name
14096                        && destPi.packageName == filterPi.packageName) {
14097                    return false;
14098                }
14099            }
14100            return true;
14101        }
14102
14103        @Override
14104        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
14105            return new PackageParser.ProviderIntentInfo[size];
14106        }
14107
14108        @Override
14109        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
14110            if (!sUserManager.exists(userId))
14111                return true;
14112            PackageParser.Package p = filter.provider.owner;
14113            if (p != null) {
14114                PackageSetting ps = (PackageSetting) p.mExtras;
14115                if (ps != null) {
14116                    // System apps are never considered stopped for purposes of
14117                    // filtering, because there may be no way for the user to
14118                    // actually re-launch them.
14119                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
14120                            && ps.getStopped(userId);
14121                }
14122            }
14123            return false;
14124        }
14125
14126        @Override
14127        protected boolean isPackageForFilter(String packageName,
14128                PackageParser.ProviderIntentInfo info) {
14129            return packageName.equals(info.provider.owner.packageName);
14130        }
14131
14132        @Override
14133        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
14134                int match, int userId) {
14135            if (!sUserManager.exists(userId))
14136                return null;
14137            final PackageParser.ProviderIntentInfo info = filter;
14138            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
14139                return null;
14140            }
14141            final PackageParser.Provider provider = info.provider;
14142            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
14143            if (ps == null) {
14144                return null;
14145            }
14146            final PackageUserState userState = ps.readUserState(userId);
14147            final boolean matchVisibleToInstantApp =
14148                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
14149            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
14150            // throw out filters that aren't visible to instant applications
14151            if (matchVisibleToInstantApp
14152                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
14153                return null;
14154            }
14155            // throw out instant application filters if we're not explicitly requesting them
14156            if (!isInstantApp && userState.instantApp) {
14157                return null;
14158            }
14159            // throw out instant application filters if updates are available; will trigger
14160            // instant application resolution
14161            if (userState.instantApp && ps.isUpdateAvailable()) {
14162                return null;
14163            }
14164            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
14165                    userState, userId);
14166            if (pi == null) {
14167                return null;
14168            }
14169            final ResolveInfo res = new ResolveInfo();
14170            res.providerInfo = pi;
14171            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
14172                res.filter = filter;
14173            }
14174            res.priority = info.getPriority();
14175            res.preferredOrder = provider.owner.mPreferredOrder;
14176            res.match = match;
14177            res.isDefault = info.hasDefault;
14178            res.labelRes = info.labelRes;
14179            res.nonLocalizedLabel = info.nonLocalizedLabel;
14180            res.icon = info.icon;
14181            res.system = res.providerInfo.applicationInfo.isSystemApp();
14182            return res;
14183        }
14184
14185        @Override
14186        protected void sortResults(List<ResolveInfo> results) {
14187            Collections.sort(results, mResolvePrioritySorter);
14188        }
14189
14190        @Override
14191        protected void dumpFilter(PrintWriter out, String prefix,
14192                PackageParser.ProviderIntentInfo filter) {
14193            out.print(prefix);
14194            out.print(
14195                    Integer.toHexString(System.identityHashCode(filter.provider)));
14196            out.print(' ');
14197            filter.provider.printComponentShortName(out);
14198            out.print(" filter ");
14199            out.println(Integer.toHexString(System.identityHashCode(filter)));
14200        }
14201
14202        @Override
14203        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
14204            return filter.provider;
14205        }
14206
14207        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
14208            PackageParser.Provider provider = (PackageParser.Provider)label;
14209            out.print(prefix); out.print(
14210                    Integer.toHexString(System.identityHashCode(provider)));
14211                    out.print(' ');
14212                    provider.printComponentShortName(out);
14213            if (count > 1) {
14214                out.print(" ("); out.print(count); out.print(" filters)");
14215            }
14216            out.println();
14217        }
14218
14219        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
14220                = new ArrayMap<ComponentName, PackageParser.Provider>();
14221        private int mFlags;
14222    }
14223
14224    static final class EphemeralIntentResolver
14225            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
14226        /**
14227         * The result that has the highest defined order. Ordering applies on a
14228         * per-package basis. Mapping is from package name to Pair of order and
14229         * EphemeralResolveInfo.
14230         * <p>
14231         * NOTE: This is implemented as a field variable for convenience and efficiency.
14232         * By having a field variable, we're able to track filter ordering as soon as
14233         * a non-zero order is defined. Otherwise, multiple loops across the result set
14234         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
14235         * this needs to be contained entirely within {@link #filterResults}.
14236         */
14237        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
14238
14239        @Override
14240        protected AuxiliaryResolveInfo[] newArray(int size) {
14241            return new AuxiliaryResolveInfo[size];
14242        }
14243
14244        @Override
14245        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
14246            return true;
14247        }
14248
14249        @Override
14250        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
14251                int userId) {
14252            if (!sUserManager.exists(userId)) {
14253                return null;
14254            }
14255            final String packageName = responseObj.resolveInfo.getPackageName();
14256            final Integer order = responseObj.getOrder();
14257            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
14258                    mOrderResult.get(packageName);
14259            // ordering is enabled and this item's order isn't high enough
14260            if (lastOrderResult != null && lastOrderResult.first >= order) {
14261                return null;
14262            }
14263            final InstantAppResolveInfo res = responseObj.resolveInfo;
14264            if (order > 0) {
14265                // non-zero order, enable ordering
14266                mOrderResult.put(packageName, new Pair<>(order, res));
14267            }
14268            return responseObj;
14269        }
14270
14271        @Override
14272        protected void filterResults(List<AuxiliaryResolveInfo> results) {
14273            // only do work if ordering is enabled [most of the time it won't be]
14274            if (mOrderResult.size() == 0) {
14275                return;
14276            }
14277            int resultSize = results.size();
14278            for (int i = 0; i < resultSize; i++) {
14279                final InstantAppResolveInfo info = results.get(i).resolveInfo;
14280                final String packageName = info.getPackageName();
14281                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
14282                if (savedInfo == null) {
14283                    // package doesn't having ordering
14284                    continue;
14285                }
14286                if (savedInfo.second == info) {
14287                    // circled back to the highest ordered item; remove from order list
14288                    mOrderResult.remove(savedInfo);
14289                    if (mOrderResult.size() == 0) {
14290                        // no more ordered items
14291                        break;
14292                    }
14293                    continue;
14294                }
14295                // item has a worse order, remove it from the result list
14296                results.remove(i);
14297                resultSize--;
14298                i--;
14299            }
14300        }
14301    }
14302
14303    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
14304            new Comparator<ResolveInfo>() {
14305        public int compare(ResolveInfo r1, ResolveInfo r2) {
14306            int v1 = r1.priority;
14307            int v2 = r2.priority;
14308            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14309            if (v1 != v2) {
14310                return (v1 > v2) ? -1 : 1;
14311            }
14312            v1 = r1.preferredOrder;
14313            v2 = r2.preferredOrder;
14314            if (v1 != v2) {
14315                return (v1 > v2) ? -1 : 1;
14316            }
14317            if (r1.isDefault != r2.isDefault) {
14318                return r1.isDefault ? -1 : 1;
14319            }
14320            v1 = r1.match;
14321            v2 = r2.match;
14322            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14323            if (v1 != v2) {
14324                return (v1 > v2) ? -1 : 1;
14325            }
14326            if (r1.system != r2.system) {
14327                return r1.system ? -1 : 1;
14328            }
14329            if (r1.activityInfo != null) {
14330                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14331            }
14332            if (r1.serviceInfo != null) {
14333                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14334            }
14335            if (r1.providerInfo != null) {
14336                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14337            }
14338            return 0;
14339        }
14340    };
14341
14342    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14343            new Comparator<ProviderInfo>() {
14344        public int compare(ProviderInfo p1, ProviderInfo p2) {
14345            final int v1 = p1.initOrder;
14346            final int v2 = p2.initOrder;
14347            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14348        }
14349    };
14350
14351    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14352            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14353            final int[] userIds) {
14354        mHandler.post(new Runnable() {
14355            @Override
14356            public void run() {
14357                try {
14358                    final IActivityManager am = ActivityManager.getService();
14359                    if (am == null) return;
14360                    final int[] resolvedUserIds;
14361                    if (userIds == null) {
14362                        resolvedUserIds = am.getRunningUserIds();
14363                    } else {
14364                        resolvedUserIds = userIds;
14365                    }
14366                    for (int id : resolvedUserIds) {
14367                        final Intent intent = new Intent(action,
14368                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14369                        if (extras != null) {
14370                            intent.putExtras(extras);
14371                        }
14372                        if (targetPkg != null) {
14373                            intent.setPackage(targetPkg);
14374                        }
14375                        // Modify the UID when posting to other users
14376                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14377                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14378                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14379                            intent.putExtra(Intent.EXTRA_UID, uid);
14380                        }
14381                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14382                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14383                        if (DEBUG_BROADCASTS) {
14384                            RuntimeException here = new RuntimeException("here");
14385                            here.fillInStackTrace();
14386                            Slog.d(TAG, "Sending to user " + id + ": "
14387                                    + intent.toShortString(false, true, false, false)
14388                                    + " " + intent.getExtras(), here);
14389                        }
14390                        am.broadcastIntent(null, intent, null, finishedReceiver,
14391                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14392                                null, finishedReceiver != null, false, id);
14393                    }
14394                } catch (RemoteException ex) {
14395                }
14396            }
14397        });
14398    }
14399
14400    /**
14401     * Check if the external storage media is available. This is true if there
14402     * is a mounted external storage medium or if the external storage is
14403     * emulated.
14404     */
14405    private boolean isExternalMediaAvailable() {
14406        return mMediaMounted || Environment.isExternalStorageEmulated();
14407    }
14408
14409    @Override
14410    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14411        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14412            return null;
14413        }
14414        // writer
14415        synchronized (mPackages) {
14416            if (!isExternalMediaAvailable()) {
14417                // If the external storage is no longer mounted at this point,
14418                // the caller may not have been able to delete all of this
14419                // packages files and can not delete any more.  Bail.
14420                return null;
14421            }
14422            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14423            if (lastPackage != null) {
14424                pkgs.remove(lastPackage);
14425            }
14426            if (pkgs.size() > 0) {
14427                return pkgs.get(0);
14428            }
14429        }
14430        return null;
14431    }
14432
14433    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14434        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14435                userId, andCode ? 1 : 0, packageName);
14436        if (mSystemReady) {
14437            msg.sendToTarget();
14438        } else {
14439            if (mPostSystemReadyMessages == null) {
14440                mPostSystemReadyMessages = new ArrayList<>();
14441            }
14442            mPostSystemReadyMessages.add(msg);
14443        }
14444    }
14445
14446    void startCleaningPackages() {
14447        // reader
14448        if (!isExternalMediaAvailable()) {
14449            return;
14450        }
14451        synchronized (mPackages) {
14452            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14453                return;
14454            }
14455        }
14456        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14457        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14458        IActivityManager am = ActivityManager.getService();
14459        if (am != null) {
14460            int dcsUid = -1;
14461            synchronized (mPackages) {
14462                if (!mDefaultContainerWhitelisted) {
14463                    mDefaultContainerWhitelisted = true;
14464                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14465                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14466                }
14467            }
14468            try {
14469                if (dcsUid > 0) {
14470                    am.backgroundWhitelistUid(dcsUid);
14471                }
14472                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14473                        UserHandle.USER_SYSTEM);
14474            } catch (RemoteException e) {
14475            }
14476        }
14477    }
14478
14479    @Override
14480    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14481            int installFlags, String installerPackageName, int userId) {
14482        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14483
14484        final int callingUid = Binder.getCallingUid();
14485        enforceCrossUserPermission(callingUid, userId,
14486                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14487
14488        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14489            try {
14490                if (observer != null) {
14491                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14492                }
14493            } catch (RemoteException re) {
14494            }
14495            return;
14496        }
14497
14498        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14499            installFlags |= PackageManager.INSTALL_FROM_ADB;
14500
14501        } else {
14502            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14503            // about installerPackageName.
14504
14505            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14506            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14507        }
14508
14509        UserHandle user;
14510        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14511            user = UserHandle.ALL;
14512        } else {
14513            user = new UserHandle(userId);
14514        }
14515
14516        // Only system components can circumvent runtime permissions when installing.
14517        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14518                && mContext.checkCallingOrSelfPermission(Manifest.permission
14519                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14520            throw new SecurityException("You need the "
14521                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14522                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14523        }
14524
14525        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14526                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14527            throw new IllegalArgumentException(
14528                    "New installs into ASEC containers no longer supported");
14529        }
14530
14531        final File originFile = new File(originPath);
14532        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14533
14534        final Message msg = mHandler.obtainMessage(INIT_COPY);
14535        final VerificationInfo verificationInfo = new VerificationInfo(
14536                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14537        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14538                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14539                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14540                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14541        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14542        msg.obj = params;
14543
14544        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14545                System.identityHashCode(msg.obj));
14546        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14547                System.identityHashCode(msg.obj));
14548
14549        mHandler.sendMessage(msg);
14550    }
14551
14552
14553    /**
14554     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14555     * it is acting on behalf on an enterprise or the user).
14556     *
14557     * Note that the ordering of the conditionals in this method is important. The checks we perform
14558     * are as follows, in this order:
14559     *
14560     * 1) If the install is being performed by a system app, we can trust the app to have set the
14561     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14562     *    what it is.
14563     * 2) If the install is being performed by a device or profile owner app, the install reason
14564     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14565     *    set the install reason correctly. If the app targets an older SDK version where install
14566     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14567     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14568     * 3) In all other cases, the install is being performed by a regular app that is neither part
14569     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14570     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14571     *    set to enterprise policy and if so, change it to unknown instead.
14572     */
14573    private int fixUpInstallReason(String installerPackageName, int installerUid,
14574            int installReason) {
14575        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14576                == PERMISSION_GRANTED) {
14577            // If the install is being performed by a system app, we trust that app to have set the
14578            // install reason correctly.
14579            return installReason;
14580        }
14581
14582        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14583            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14584        if (dpm != null) {
14585            ComponentName owner = null;
14586            try {
14587                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14588                if (owner == null) {
14589                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14590                }
14591            } catch (RemoteException e) {
14592            }
14593            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14594                // If the install is being performed by a device or profile owner, the install
14595                // reason should be enterprise policy.
14596                return PackageManager.INSTALL_REASON_POLICY;
14597            }
14598        }
14599
14600        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14601            // If the install is being performed by a regular app (i.e. neither system app nor
14602            // device or profile owner), we have no reason to believe that the app is acting on
14603            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14604            // change it to unknown instead.
14605            return PackageManager.INSTALL_REASON_UNKNOWN;
14606        }
14607
14608        // If the install is being performed by a regular app and the install reason was set to any
14609        // value but enterprise policy, leave the install reason unchanged.
14610        return installReason;
14611    }
14612
14613    void installStage(String packageName, File stagedDir, String stagedCid,
14614            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14615            String installerPackageName, int installerUid, UserHandle user,
14616            Certificate[][] certificates) {
14617        if (DEBUG_EPHEMERAL) {
14618            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14619                Slog.d(TAG, "Ephemeral install of " + packageName);
14620            }
14621        }
14622        final VerificationInfo verificationInfo = new VerificationInfo(
14623                sessionParams.originatingUri, sessionParams.referrerUri,
14624                sessionParams.originatingUid, installerUid);
14625
14626        final OriginInfo origin;
14627        if (stagedDir != null) {
14628            origin = OriginInfo.fromStagedFile(stagedDir);
14629        } else {
14630            origin = OriginInfo.fromStagedContainer(stagedCid);
14631        }
14632
14633        final Message msg = mHandler.obtainMessage(INIT_COPY);
14634        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14635                sessionParams.installReason);
14636        final InstallParams params = new InstallParams(origin, null, observer,
14637                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14638                verificationInfo, user, sessionParams.abiOverride,
14639                sessionParams.grantedRuntimePermissions, certificates, installReason);
14640        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14641        msg.obj = params;
14642
14643        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14644                System.identityHashCode(msg.obj));
14645        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14646                System.identityHashCode(msg.obj));
14647
14648        mHandler.sendMessage(msg);
14649    }
14650
14651    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14652            int userId) {
14653        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14654        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
14655                false /*startReceiver*/, pkgSetting.appId, userId);
14656
14657        // Send a session commit broadcast
14658        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14659        info.installReason = pkgSetting.getInstallReason(userId);
14660        info.appPackageName = packageName;
14661        sendSessionCommitBroadcast(info, userId);
14662    }
14663
14664    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
14665            boolean includeStopped, int appId, int... userIds) {
14666        if (ArrayUtils.isEmpty(userIds)) {
14667            return;
14668        }
14669        Bundle extras = new Bundle(1);
14670        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14671        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14672
14673        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14674                packageName, extras, 0, null, null, userIds);
14675        if (sendBootCompleted) {
14676            mHandler.post(() -> {
14677                        for (int userId : userIds) {
14678                            sendBootCompletedBroadcastToSystemApp(
14679                                    packageName, includeStopped, userId);
14680                        }
14681                    }
14682            );
14683        }
14684    }
14685
14686    /**
14687     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14688     * automatically without needing an explicit launch.
14689     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14690     */
14691    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
14692            int userId) {
14693        // If user is not running, the app didn't miss any broadcast
14694        if (!mUserManagerInternal.isUserRunning(userId)) {
14695            return;
14696        }
14697        final IActivityManager am = ActivityManager.getService();
14698        try {
14699            // Deliver LOCKED_BOOT_COMPLETED first
14700            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14701                    .setPackage(packageName);
14702            if (includeStopped) {
14703                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14704            }
14705            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14706            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14707                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14708
14709            // Deliver BOOT_COMPLETED only if user is unlocked
14710            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14711                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14712                if (includeStopped) {
14713                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
14714                }
14715                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14716                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14717            }
14718        } catch (RemoteException e) {
14719            throw e.rethrowFromSystemServer();
14720        }
14721    }
14722
14723    @Override
14724    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14725            int userId) {
14726        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14727        PackageSetting pkgSetting;
14728        final int callingUid = Binder.getCallingUid();
14729        enforceCrossUserPermission(callingUid, userId,
14730                true /* requireFullPermission */, true /* checkShell */,
14731                "setApplicationHiddenSetting for user " + userId);
14732
14733        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14734            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14735            return false;
14736        }
14737
14738        long callingId = Binder.clearCallingIdentity();
14739        try {
14740            boolean sendAdded = false;
14741            boolean sendRemoved = false;
14742            // writer
14743            synchronized (mPackages) {
14744                pkgSetting = mSettings.mPackages.get(packageName);
14745                if (pkgSetting == null) {
14746                    return false;
14747                }
14748                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14749                    return false;
14750                }
14751                // Do not allow "android" is being disabled
14752                if ("android".equals(packageName)) {
14753                    Slog.w(TAG, "Cannot hide package: android");
14754                    return false;
14755                }
14756                // Cannot hide static shared libs as they are considered
14757                // a part of the using app (emulating static linking). Also
14758                // static libs are installed always on internal storage.
14759                PackageParser.Package pkg = mPackages.get(packageName);
14760                if (pkg != null && pkg.staticSharedLibName != null) {
14761                    Slog.w(TAG, "Cannot hide package: " + packageName
14762                            + " providing static shared library: "
14763                            + pkg.staticSharedLibName);
14764                    return false;
14765                }
14766                // Only allow protected packages to hide themselves.
14767                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14768                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14769                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14770                    return false;
14771                }
14772
14773                if (pkgSetting.getHidden(userId) != hidden) {
14774                    pkgSetting.setHidden(hidden, userId);
14775                    mSettings.writePackageRestrictionsLPr(userId);
14776                    if (hidden) {
14777                        sendRemoved = true;
14778                    } else {
14779                        sendAdded = true;
14780                    }
14781                }
14782            }
14783            if (sendAdded) {
14784                sendPackageAddedForUser(packageName, pkgSetting, userId);
14785                return true;
14786            }
14787            if (sendRemoved) {
14788                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14789                        "hiding pkg");
14790                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14791                return true;
14792            }
14793        } finally {
14794            Binder.restoreCallingIdentity(callingId);
14795        }
14796        return false;
14797    }
14798
14799    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14800            int userId) {
14801        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14802        info.removedPackage = packageName;
14803        info.installerPackageName = pkgSetting.installerPackageName;
14804        info.removedUsers = new int[] {userId};
14805        info.broadcastUsers = new int[] {userId};
14806        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14807        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14808    }
14809
14810    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14811        if (pkgList.length > 0) {
14812            Bundle extras = new Bundle(1);
14813            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14814
14815            sendPackageBroadcast(
14816                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14817                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14818                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14819                    new int[] {userId});
14820        }
14821    }
14822
14823    /**
14824     * Returns true if application is not found or there was an error. Otherwise it returns
14825     * the hidden state of the package for the given user.
14826     */
14827    @Override
14828    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14829        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14830        final int callingUid = Binder.getCallingUid();
14831        enforceCrossUserPermission(callingUid, userId,
14832                true /* requireFullPermission */, false /* checkShell */,
14833                "getApplicationHidden for user " + userId);
14834        PackageSetting ps;
14835        long callingId = Binder.clearCallingIdentity();
14836        try {
14837            // writer
14838            synchronized (mPackages) {
14839                ps = mSettings.mPackages.get(packageName);
14840                if (ps == null) {
14841                    return true;
14842                }
14843                if (filterAppAccessLPr(ps, callingUid, userId)) {
14844                    return true;
14845                }
14846                return ps.getHidden(userId);
14847            }
14848        } finally {
14849            Binder.restoreCallingIdentity(callingId);
14850        }
14851    }
14852
14853    /**
14854     * @hide
14855     */
14856    @Override
14857    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14858            int installReason) {
14859        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14860                null);
14861        PackageSetting pkgSetting;
14862        final int callingUid = Binder.getCallingUid();
14863        enforceCrossUserPermission(callingUid, userId,
14864                true /* requireFullPermission */, true /* checkShell */,
14865                "installExistingPackage for user " + userId);
14866        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14867            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14868        }
14869
14870        long callingId = Binder.clearCallingIdentity();
14871        try {
14872            boolean installed = false;
14873            final boolean instantApp =
14874                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14875            final boolean fullApp =
14876                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14877
14878            // writer
14879            synchronized (mPackages) {
14880                pkgSetting = mSettings.mPackages.get(packageName);
14881                if (pkgSetting == null) {
14882                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14883                }
14884                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14885                    // only allow the existing package to be used if it's installed as a full
14886                    // application for at least one user
14887                    boolean installAllowed = false;
14888                    for (int checkUserId : sUserManager.getUserIds()) {
14889                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14890                        if (installAllowed) {
14891                            break;
14892                        }
14893                    }
14894                    if (!installAllowed) {
14895                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14896                    }
14897                }
14898                if (!pkgSetting.getInstalled(userId)) {
14899                    pkgSetting.setInstalled(true, userId);
14900                    pkgSetting.setHidden(false, userId);
14901                    pkgSetting.setInstallReason(installReason, userId);
14902                    mSettings.writePackageRestrictionsLPr(userId);
14903                    mSettings.writeKernelMappingLPr(pkgSetting);
14904                    installed = true;
14905                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14906                    // upgrade app from instant to full; we don't allow app downgrade
14907                    installed = true;
14908                }
14909                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14910            }
14911
14912            if (installed) {
14913                if (pkgSetting.pkg != null) {
14914                    synchronized (mInstallLock) {
14915                        // We don't need to freeze for a brand new install
14916                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14917                    }
14918                }
14919                sendPackageAddedForUser(packageName, pkgSetting, userId);
14920                synchronized (mPackages) {
14921                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14922                }
14923            }
14924        } finally {
14925            Binder.restoreCallingIdentity(callingId);
14926        }
14927
14928        return PackageManager.INSTALL_SUCCEEDED;
14929    }
14930
14931    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14932            boolean instantApp, boolean fullApp) {
14933        // no state specified; do nothing
14934        if (!instantApp && !fullApp) {
14935            return;
14936        }
14937        if (userId != UserHandle.USER_ALL) {
14938            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14939                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14940            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14941                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14942            }
14943        } else {
14944            for (int currentUserId : sUserManager.getUserIds()) {
14945                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14946                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14947                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14948                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14949                }
14950            }
14951        }
14952    }
14953
14954    boolean isUserRestricted(int userId, String restrictionKey) {
14955        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14956        if (restrictions.getBoolean(restrictionKey, false)) {
14957            Log.w(TAG, "User is restricted: " + restrictionKey);
14958            return true;
14959        }
14960        return false;
14961    }
14962
14963    @Override
14964    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14965            int userId) {
14966        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14967        final int callingUid = Binder.getCallingUid();
14968        enforceCrossUserPermission(callingUid, userId,
14969                true /* requireFullPermission */, true /* checkShell */,
14970                "setPackagesSuspended for user " + userId);
14971
14972        if (ArrayUtils.isEmpty(packageNames)) {
14973            return packageNames;
14974        }
14975
14976        // List of package names for whom the suspended state has changed.
14977        List<String> changedPackages = new ArrayList<>(packageNames.length);
14978        // List of package names for whom the suspended state is not set as requested in this
14979        // method.
14980        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14981        long callingId = Binder.clearCallingIdentity();
14982        try {
14983            for (int i = 0; i < packageNames.length; i++) {
14984                String packageName = packageNames[i];
14985                boolean changed = false;
14986                final int appId;
14987                synchronized (mPackages) {
14988                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14989                    if (pkgSetting == null
14990                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14991                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14992                                + "\". Skipping suspending/un-suspending.");
14993                        unactionedPackages.add(packageName);
14994                        continue;
14995                    }
14996                    appId = pkgSetting.appId;
14997                    if (pkgSetting.getSuspended(userId) != suspended) {
14998                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14999                            unactionedPackages.add(packageName);
15000                            continue;
15001                        }
15002                        pkgSetting.setSuspended(suspended, userId);
15003                        mSettings.writePackageRestrictionsLPr(userId);
15004                        changed = true;
15005                        changedPackages.add(packageName);
15006                    }
15007                }
15008
15009                if (changed && suspended) {
15010                    killApplication(packageName, UserHandle.getUid(userId, appId),
15011                            "suspending package");
15012                }
15013            }
15014        } finally {
15015            Binder.restoreCallingIdentity(callingId);
15016        }
15017
15018        if (!changedPackages.isEmpty()) {
15019            sendPackagesSuspendedForUser(changedPackages.toArray(
15020                    new String[changedPackages.size()]), userId, suspended);
15021        }
15022
15023        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
15024    }
15025
15026    @Override
15027    public boolean isPackageSuspendedForUser(String packageName, int userId) {
15028        final int callingUid = Binder.getCallingUid();
15029        enforceCrossUserPermission(callingUid, userId,
15030                true /* requireFullPermission */, false /* checkShell */,
15031                "isPackageSuspendedForUser for user " + userId);
15032        synchronized (mPackages) {
15033            final PackageSetting ps = mSettings.mPackages.get(packageName);
15034            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
15035                throw new IllegalArgumentException("Unknown target package: " + packageName);
15036            }
15037            return ps.getSuspended(userId);
15038        }
15039    }
15040
15041    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
15042        if (isPackageDeviceAdmin(packageName, userId)) {
15043            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15044                    + "\": has an active device admin");
15045            return false;
15046        }
15047
15048        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
15049        if (packageName.equals(activeLauncherPackageName)) {
15050            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15051                    + "\": contains the active launcher");
15052            return false;
15053        }
15054
15055        if (packageName.equals(mRequiredInstallerPackage)) {
15056            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15057                    + "\": required for package installation");
15058            return false;
15059        }
15060
15061        if (packageName.equals(mRequiredUninstallerPackage)) {
15062            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15063                    + "\": required for package uninstallation");
15064            return false;
15065        }
15066
15067        if (packageName.equals(mRequiredVerifierPackage)) {
15068            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15069                    + "\": required for package verification");
15070            return false;
15071        }
15072
15073        if (packageName.equals(getDefaultDialerPackageName(userId))) {
15074            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15075                    + "\": is the default dialer");
15076            return false;
15077        }
15078
15079        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
15080            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
15081                    + "\": protected package");
15082            return false;
15083        }
15084
15085        // Cannot suspend static shared libs as they are considered
15086        // a part of the using app (emulating static linking). Also
15087        // static libs are installed always on internal storage.
15088        PackageParser.Package pkg = mPackages.get(packageName);
15089        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
15090            Slog.w(TAG, "Cannot suspend package: " + packageName
15091                    + " providing static shared library: "
15092                    + pkg.staticSharedLibName);
15093            return false;
15094        }
15095
15096        return true;
15097    }
15098
15099    private String getActiveLauncherPackageName(int userId) {
15100        Intent intent = new Intent(Intent.ACTION_MAIN);
15101        intent.addCategory(Intent.CATEGORY_HOME);
15102        ResolveInfo resolveInfo = resolveIntent(
15103                intent,
15104                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
15105                PackageManager.MATCH_DEFAULT_ONLY,
15106                userId);
15107
15108        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
15109    }
15110
15111    private String getDefaultDialerPackageName(int userId) {
15112        synchronized (mPackages) {
15113            return mSettings.getDefaultDialerPackageNameLPw(userId);
15114        }
15115    }
15116
15117    @Override
15118    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
15119        mContext.enforceCallingOrSelfPermission(
15120                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15121                "Only package verification agents can verify applications");
15122
15123        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15124        final PackageVerificationResponse response = new PackageVerificationResponse(
15125                verificationCode, Binder.getCallingUid());
15126        msg.arg1 = id;
15127        msg.obj = response;
15128        mHandler.sendMessage(msg);
15129    }
15130
15131    @Override
15132    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
15133            long millisecondsToDelay) {
15134        mContext.enforceCallingOrSelfPermission(
15135                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15136                "Only package verification agents can extend verification timeouts");
15137
15138        final PackageVerificationState state = mPendingVerification.get(id);
15139        final PackageVerificationResponse response = new PackageVerificationResponse(
15140                verificationCodeAtTimeout, Binder.getCallingUid());
15141
15142        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
15143            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
15144        }
15145        if (millisecondsToDelay < 0) {
15146            millisecondsToDelay = 0;
15147        }
15148        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
15149                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
15150            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
15151        }
15152
15153        if ((state != null) && !state.timeoutExtended()) {
15154            state.extendTimeout();
15155
15156            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
15157            msg.arg1 = id;
15158            msg.obj = response;
15159            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
15160        }
15161    }
15162
15163    private void broadcastPackageVerified(int verificationId, Uri packageUri,
15164            int verificationCode, UserHandle user) {
15165        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
15166        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
15167        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15168        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15169        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
15170
15171        mContext.sendBroadcastAsUser(intent, user,
15172                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
15173    }
15174
15175    private ComponentName matchComponentForVerifier(String packageName,
15176            List<ResolveInfo> receivers) {
15177        ActivityInfo targetReceiver = null;
15178
15179        final int NR = receivers.size();
15180        for (int i = 0; i < NR; i++) {
15181            final ResolveInfo info = receivers.get(i);
15182            if (info.activityInfo == null) {
15183                continue;
15184            }
15185
15186            if (packageName.equals(info.activityInfo.packageName)) {
15187                targetReceiver = info.activityInfo;
15188                break;
15189            }
15190        }
15191
15192        if (targetReceiver == null) {
15193            return null;
15194        }
15195
15196        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
15197    }
15198
15199    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
15200            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
15201        if (pkgInfo.verifiers.length == 0) {
15202            return null;
15203        }
15204
15205        final int N = pkgInfo.verifiers.length;
15206        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
15207        for (int i = 0; i < N; i++) {
15208            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
15209
15210            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
15211                    receivers);
15212            if (comp == null) {
15213                continue;
15214            }
15215
15216            final int verifierUid = getUidForVerifier(verifierInfo);
15217            if (verifierUid == -1) {
15218                continue;
15219            }
15220
15221            if (DEBUG_VERIFY) {
15222                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
15223                        + " with the correct signature");
15224            }
15225            sufficientVerifiers.add(comp);
15226            verificationState.addSufficientVerifier(verifierUid);
15227        }
15228
15229        return sufficientVerifiers;
15230    }
15231
15232    private int getUidForVerifier(VerifierInfo verifierInfo) {
15233        synchronized (mPackages) {
15234            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
15235            if (pkg == null) {
15236                return -1;
15237            } else if (pkg.mSignatures.length != 1) {
15238                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15239                        + " has more than one signature; ignoring");
15240                return -1;
15241            }
15242
15243            /*
15244             * If the public key of the package's signature does not match
15245             * our expected public key, then this is a different package and
15246             * we should skip.
15247             */
15248
15249            final byte[] expectedPublicKey;
15250            try {
15251                final Signature verifierSig = pkg.mSignatures[0];
15252                final PublicKey publicKey = verifierSig.getPublicKey();
15253                expectedPublicKey = publicKey.getEncoded();
15254            } catch (CertificateException e) {
15255                return -1;
15256            }
15257
15258            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
15259
15260            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
15261                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
15262                        + " does not have the expected public key; ignoring");
15263                return -1;
15264            }
15265
15266            return pkg.applicationInfo.uid;
15267        }
15268    }
15269
15270    @Override
15271    public void finishPackageInstall(int token, boolean didLaunch) {
15272        enforceSystemOrRoot("Only the system is allowed to finish installs");
15273
15274        if (DEBUG_INSTALL) {
15275            Slog.v(TAG, "BM finishing package install for " + token);
15276        }
15277        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15278
15279        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
15280        mHandler.sendMessage(msg);
15281    }
15282
15283    /**
15284     * Get the verification agent timeout.  Used for both the APK verifier and the
15285     * intent filter verifier.
15286     *
15287     * @return verification timeout in milliseconds
15288     */
15289    private long getVerificationTimeout() {
15290        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
15291                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
15292                DEFAULT_VERIFICATION_TIMEOUT);
15293    }
15294
15295    /**
15296     * Get the default verification agent response code.
15297     *
15298     * @return default verification response code
15299     */
15300    private int getDefaultVerificationResponse(UserHandle user) {
15301        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
15302            return PackageManager.VERIFICATION_REJECT;
15303        }
15304        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15305                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
15306                DEFAULT_VERIFICATION_RESPONSE);
15307    }
15308
15309    /**
15310     * Check whether or not package verification has been enabled.
15311     *
15312     * @return true if verification should be performed
15313     */
15314    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
15315        if (!DEFAULT_VERIFY_ENABLE) {
15316            return false;
15317        }
15318
15319        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15320
15321        // Check if installing from ADB
15322        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15323            // Do not run verification in a test harness environment
15324            if (ActivityManager.isRunningInTestHarness()) {
15325                return false;
15326            }
15327            if (ensureVerifyAppsEnabled) {
15328                return true;
15329            }
15330            // Check if the developer does not want package verification for ADB installs
15331            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15332                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15333                return false;
15334            }
15335        } else {
15336            // only when not installed from ADB, skip verification for instant apps when
15337            // the installer and verifier are the same.
15338            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15339                if (mInstantAppInstallerActivity != null
15340                        && mInstantAppInstallerActivity.packageName.equals(
15341                                mRequiredVerifierPackage)) {
15342                    try {
15343                        mContext.getSystemService(AppOpsManager.class)
15344                                .checkPackage(installerUid, mRequiredVerifierPackage);
15345                        if (DEBUG_VERIFY) {
15346                            Slog.i(TAG, "disable verification for instant app");
15347                        }
15348                        return false;
15349                    } catch (SecurityException ignore) { }
15350                }
15351            }
15352        }
15353
15354        if (ensureVerifyAppsEnabled) {
15355            return true;
15356        }
15357
15358        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15359                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15360    }
15361
15362    @Override
15363    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15364            throws RemoteException {
15365        mContext.enforceCallingOrSelfPermission(
15366                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15367                "Only intentfilter verification agents can verify applications");
15368
15369        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15370        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15371                Binder.getCallingUid(), verificationCode, failedDomains);
15372        msg.arg1 = id;
15373        msg.obj = response;
15374        mHandler.sendMessage(msg);
15375    }
15376
15377    @Override
15378    public int getIntentVerificationStatus(String packageName, int userId) {
15379        final int callingUid = Binder.getCallingUid();
15380        if (UserHandle.getUserId(callingUid) != userId) {
15381            mContext.enforceCallingOrSelfPermission(
15382                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15383                    "getIntentVerificationStatus" + userId);
15384        }
15385        if (getInstantAppPackageName(callingUid) != null) {
15386            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15387        }
15388        synchronized (mPackages) {
15389            final PackageSetting ps = mSettings.mPackages.get(packageName);
15390            if (ps == null
15391                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15392                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15393            }
15394            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15395        }
15396    }
15397
15398    @Override
15399    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15400        mContext.enforceCallingOrSelfPermission(
15401                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15402
15403        boolean result = false;
15404        synchronized (mPackages) {
15405            final PackageSetting ps = mSettings.mPackages.get(packageName);
15406            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15407                return false;
15408            }
15409            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15410        }
15411        if (result) {
15412            scheduleWritePackageRestrictionsLocked(userId);
15413        }
15414        return result;
15415    }
15416
15417    @Override
15418    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15419            String packageName) {
15420        final int callingUid = Binder.getCallingUid();
15421        if (getInstantAppPackageName(callingUid) != null) {
15422            return ParceledListSlice.emptyList();
15423        }
15424        synchronized (mPackages) {
15425            final PackageSetting ps = mSettings.mPackages.get(packageName);
15426            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15427                return ParceledListSlice.emptyList();
15428            }
15429            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15430        }
15431    }
15432
15433    @Override
15434    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15435        if (TextUtils.isEmpty(packageName)) {
15436            return ParceledListSlice.emptyList();
15437        }
15438        final int callingUid = Binder.getCallingUid();
15439        final int callingUserId = UserHandle.getUserId(callingUid);
15440        synchronized (mPackages) {
15441            PackageParser.Package pkg = mPackages.get(packageName);
15442            if (pkg == null || pkg.activities == null) {
15443                return ParceledListSlice.emptyList();
15444            }
15445            if (pkg.mExtras == null) {
15446                return ParceledListSlice.emptyList();
15447            }
15448            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15449            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15450                return ParceledListSlice.emptyList();
15451            }
15452            final int count = pkg.activities.size();
15453            ArrayList<IntentFilter> result = new ArrayList<>();
15454            for (int n=0; n<count; n++) {
15455                PackageParser.Activity activity = pkg.activities.get(n);
15456                if (activity.intents != null && activity.intents.size() > 0) {
15457                    result.addAll(activity.intents);
15458                }
15459            }
15460            return new ParceledListSlice<>(result);
15461        }
15462    }
15463
15464    @Override
15465    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15466        mContext.enforceCallingOrSelfPermission(
15467                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15468        if (UserHandle.getCallingUserId() != userId) {
15469            mContext.enforceCallingOrSelfPermission(
15470                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15471        }
15472
15473        synchronized (mPackages) {
15474            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15475            if (packageName != null) {
15476                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15477                        packageName, userId);
15478            }
15479            return result;
15480        }
15481    }
15482
15483    @Override
15484    public String getDefaultBrowserPackageName(int userId) {
15485        if (UserHandle.getCallingUserId() != userId) {
15486            mContext.enforceCallingOrSelfPermission(
15487                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15488        }
15489        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15490            return null;
15491        }
15492        synchronized (mPackages) {
15493            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15494        }
15495    }
15496
15497    /**
15498     * Get the "allow unknown sources" setting.
15499     *
15500     * @return the current "allow unknown sources" setting
15501     */
15502    private int getUnknownSourcesSettings() {
15503        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15504                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15505                -1);
15506    }
15507
15508    @Override
15509    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15510        final int callingUid = Binder.getCallingUid();
15511        if (getInstantAppPackageName(callingUid) != null) {
15512            return;
15513        }
15514        // writer
15515        synchronized (mPackages) {
15516            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15517            if (targetPackageSetting == null
15518                    || filterAppAccessLPr(
15519                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15520                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15521            }
15522
15523            PackageSetting installerPackageSetting;
15524            if (installerPackageName != null) {
15525                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15526                if (installerPackageSetting == null) {
15527                    throw new IllegalArgumentException("Unknown installer package: "
15528                            + installerPackageName);
15529                }
15530            } else {
15531                installerPackageSetting = null;
15532            }
15533
15534            Signature[] callerSignature;
15535            Object obj = mSettings.getUserIdLPr(callingUid);
15536            if (obj != null) {
15537                if (obj instanceof SharedUserSetting) {
15538                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15539                } else if (obj instanceof PackageSetting) {
15540                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15541                } else {
15542                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15543                }
15544            } else {
15545                throw new SecurityException("Unknown calling UID: " + callingUid);
15546            }
15547
15548            // Verify: can't set installerPackageName to a package that is
15549            // not signed with the same cert as the caller.
15550            if (installerPackageSetting != null) {
15551                if (compareSignatures(callerSignature,
15552                        installerPackageSetting.signatures.mSignatures)
15553                        != PackageManager.SIGNATURE_MATCH) {
15554                    throw new SecurityException(
15555                            "Caller does not have same cert as new installer package "
15556                            + installerPackageName);
15557                }
15558            }
15559
15560            // Verify: if target already has an installer package, it must
15561            // be signed with the same cert as the caller.
15562            if (targetPackageSetting.installerPackageName != null) {
15563                PackageSetting setting = mSettings.mPackages.get(
15564                        targetPackageSetting.installerPackageName);
15565                // If the currently set package isn't valid, then it's always
15566                // okay to change it.
15567                if (setting != null) {
15568                    if (compareSignatures(callerSignature,
15569                            setting.signatures.mSignatures)
15570                            != PackageManager.SIGNATURE_MATCH) {
15571                        throw new SecurityException(
15572                                "Caller does not have same cert as old installer package "
15573                                + targetPackageSetting.installerPackageName);
15574                    }
15575                }
15576            }
15577
15578            // Okay!
15579            targetPackageSetting.installerPackageName = installerPackageName;
15580            if (installerPackageName != null) {
15581                mSettings.mInstallerPackages.add(installerPackageName);
15582            }
15583            scheduleWriteSettingsLocked();
15584        }
15585    }
15586
15587    @Override
15588    public void setApplicationCategoryHint(String packageName, int categoryHint,
15589            String callerPackageName) {
15590        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15591            throw new SecurityException("Instant applications don't have access to this method");
15592        }
15593        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15594                callerPackageName);
15595        synchronized (mPackages) {
15596            PackageSetting ps = mSettings.mPackages.get(packageName);
15597            if (ps == null) {
15598                throw new IllegalArgumentException("Unknown target package " + packageName);
15599            }
15600            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15601                throw new IllegalArgumentException("Unknown target package " + packageName);
15602            }
15603            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15604                throw new IllegalArgumentException("Calling package " + callerPackageName
15605                        + " is not installer for " + packageName);
15606            }
15607
15608            if (ps.categoryHint != categoryHint) {
15609                ps.categoryHint = categoryHint;
15610                scheduleWriteSettingsLocked();
15611            }
15612        }
15613    }
15614
15615    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15616        // Queue up an async operation since the package installation may take a little while.
15617        mHandler.post(new Runnable() {
15618            public void run() {
15619                mHandler.removeCallbacks(this);
15620                 // Result object to be returned
15621                PackageInstalledInfo res = new PackageInstalledInfo();
15622                res.setReturnCode(currentStatus);
15623                res.uid = -1;
15624                res.pkg = null;
15625                res.removedInfo = null;
15626                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15627                    args.doPreInstall(res.returnCode);
15628                    synchronized (mInstallLock) {
15629                        installPackageTracedLI(args, res);
15630                    }
15631                    args.doPostInstall(res.returnCode, res.uid);
15632                }
15633
15634                // A restore should be performed at this point if (a) the install
15635                // succeeded, (b) the operation is not an update, and (c) the new
15636                // package has not opted out of backup participation.
15637                final boolean update = res.removedInfo != null
15638                        && res.removedInfo.removedPackage != null;
15639                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15640                boolean doRestore = !update
15641                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15642
15643                // Set up the post-install work request bookkeeping.  This will be used
15644                // and cleaned up by the post-install event handling regardless of whether
15645                // there's a restore pass performed.  Token values are >= 1.
15646                int token;
15647                if (mNextInstallToken < 0) mNextInstallToken = 1;
15648                token = mNextInstallToken++;
15649
15650                PostInstallData data = new PostInstallData(args, res);
15651                mRunningInstalls.put(token, data);
15652                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15653
15654                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15655                    // Pass responsibility to the Backup Manager.  It will perform a
15656                    // restore if appropriate, then pass responsibility back to the
15657                    // Package Manager to run the post-install observer callbacks
15658                    // and broadcasts.
15659                    IBackupManager bm = IBackupManager.Stub.asInterface(
15660                            ServiceManager.getService(Context.BACKUP_SERVICE));
15661                    if (bm != null) {
15662                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15663                                + " to BM for possible restore");
15664                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15665                        try {
15666                            // TODO: http://b/22388012
15667                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15668                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15669                            } else {
15670                                doRestore = false;
15671                            }
15672                        } catch (RemoteException e) {
15673                            // can't happen; the backup manager is local
15674                        } catch (Exception e) {
15675                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15676                            doRestore = false;
15677                        }
15678                    } else {
15679                        Slog.e(TAG, "Backup Manager not found!");
15680                        doRestore = false;
15681                    }
15682                }
15683
15684                if (!doRestore) {
15685                    // No restore possible, or the Backup Manager was mysteriously not
15686                    // available -- just fire the post-install work request directly.
15687                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15688
15689                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15690
15691                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15692                    mHandler.sendMessage(msg);
15693                }
15694            }
15695        });
15696    }
15697
15698    /**
15699     * Callback from PackageSettings whenever an app is first transitioned out of the
15700     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15701     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15702     * here whether the app is the target of an ongoing install, and only send the
15703     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15704     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15705     * handling.
15706     */
15707    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15708        // Serialize this with the rest of the install-process message chain.  In the
15709        // restore-at-install case, this Runnable will necessarily run before the
15710        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15711        // are coherent.  In the non-restore case, the app has already completed install
15712        // and been launched through some other means, so it is not in a problematic
15713        // state for observers to see the FIRST_LAUNCH signal.
15714        mHandler.post(new Runnable() {
15715            @Override
15716            public void run() {
15717                for (int i = 0; i < mRunningInstalls.size(); i++) {
15718                    final PostInstallData data = mRunningInstalls.valueAt(i);
15719                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15720                        continue;
15721                    }
15722                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15723                        // right package; but is it for the right user?
15724                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15725                            if (userId == data.res.newUsers[uIndex]) {
15726                                if (DEBUG_BACKUP) {
15727                                    Slog.i(TAG, "Package " + pkgName
15728                                            + " being restored so deferring FIRST_LAUNCH");
15729                                }
15730                                return;
15731                            }
15732                        }
15733                    }
15734                }
15735                // didn't find it, so not being restored
15736                if (DEBUG_BACKUP) {
15737                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15738                }
15739                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15740            }
15741        });
15742    }
15743
15744    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15745        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15746                installerPkg, null, userIds);
15747    }
15748
15749    private abstract class HandlerParams {
15750        private static final int MAX_RETRIES = 4;
15751
15752        /**
15753         * Number of times startCopy() has been attempted and had a non-fatal
15754         * error.
15755         */
15756        private int mRetries = 0;
15757
15758        /** User handle for the user requesting the information or installation. */
15759        private final UserHandle mUser;
15760        String traceMethod;
15761        int traceCookie;
15762
15763        HandlerParams(UserHandle user) {
15764            mUser = user;
15765        }
15766
15767        UserHandle getUser() {
15768            return mUser;
15769        }
15770
15771        HandlerParams setTraceMethod(String traceMethod) {
15772            this.traceMethod = traceMethod;
15773            return this;
15774        }
15775
15776        HandlerParams setTraceCookie(int traceCookie) {
15777            this.traceCookie = traceCookie;
15778            return this;
15779        }
15780
15781        final boolean startCopy() {
15782            boolean res;
15783            try {
15784                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15785
15786                if (++mRetries > MAX_RETRIES) {
15787                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15788                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15789                    handleServiceError();
15790                    return false;
15791                } else {
15792                    handleStartCopy();
15793                    res = true;
15794                }
15795            } catch (RemoteException e) {
15796                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15797                mHandler.sendEmptyMessage(MCS_RECONNECT);
15798                res = false;
15799            }
15800            handleReturnCode();
15801            return res;
15802        }
15803
15804        final void serviceError() {
15805            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15806            handleServiceError();
15807            handleReturnCode();
15808        }
15809
15810        abstract void handleStartCopy() throws RemoteException;
15811        abstract void handleServiceError();
15812        abstract void handleReturnCode();
15813    }
15814
15815    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15816        for (File path : paths) {
15817            try {
15818                mcs.clearDirectory(path.getAbsolutePath());
15819            } catch (RemoteException e) {
15820            }
15821        }
15822    }
15823
15824    static class OriginInfo {
15825        /**
15826         * Location where install is coming from, before it has been
15827         * copied/renamed into place. This could be a single monolithic APK
15828         * file, or a cluster directory. This location may be untrusted.
15829         */
15830        final File file;
15831        final String cid;
15832
15833        /**
15834         * Flag indicating that {@link #file} or {@link #cid} has already been
15835         * staged, meaning downstream users don't need to defensively copy the
15836         * contents.
15837         */
15838        final boolean staged;
15839
15840        /**
15841         * Flag indicating that {@link #file} or {@link #cid} is an already
15842         * installed app that is being moved.
15843         */
15844        final boolean existing;
15845
15846        final String resolvedPath;
15847        final File resolvedFile;
15848
15849        static OriginInfo fromNothing() {
15850            return new OriginInfo(null, null, false, false);
15851        }
15852
15853        static OriginInfo fromUntrustedFile(File file) {
15854            return new OriginInfo(file, null, false, false);
15855        }
15856
15857        static OriginInfo fromExistingFile(File file) {
15858            return new OriginInfo(file, null, false, true);
15859        }
15860
15861        static OriginInfo fromStagedFile(File file) {
15862            return new OriginInfo(file, null, true, false);
15863        }
15864
15865        static OriginInfo fromStagedContainer(String cid) {
15866            return new OriginInfo(null, cid, true, false);
15867        }
15868
15869        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15870            this.file = file;
15871            this.cid = cid;
15872            this.staged = staged;
15873            this.existing = existing;
15874
15875            if (cid != null) {
15876                resolvedPath = PackageHelper.getSdDir(cid);
15877                resolvedFile = new File(resolvedPath);
15878            } else if (file != null) {
15879                resolvedPath = file.getAbsolutePath();
15880                resolvedFile = file;
15881            } else {
15882                resolvedPath = null;
15883                resolvedFile = null;
15884            }
15885        }
15886    }
15887
15888    static class MoveInfo {
15889        final int moveId;
15890        final String fromUuid;
15891        final String toUuid;
15892        final String packageName;
15893        final String dataAppName;
15894        final int appId;
15895        final String seinfo;
15896        final int targetSdkVersion;
15897
15898        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15899                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15900            this.moveId = moveId;
15901            this.fromUuid = fromUuid;
15902            this.toUuid = toUuid;
15903            this.packageName = packageName;
15904            this.dataAppName = dataAppName;
15905            this.appId = appId;
15906            this.seinfo = seinfo;
15907            this.targetSdkVersion = targetSdkVersion;
15908        }
15909    }
15910
15911    static class VerificationInfo {
15912        /** A constant used to indicate that a uid value is not present. */
15913        public static final int NO_UID = -1;
15914
15915        /** URI referencing where the package was downloaded from. */
15916        final Uri originatingUri;
15917
15918        /** HTTP referrer URI associated with the originatingURI. */
15919        final Uri referrer;
15920
15921        /** UID of the application that the install request originated from. */
15922        final int originatingUid;
15923
15924        /** UID of application requesting the install */
15925        final int installerUid;
15926
15927        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15928            this.originatingUri = originatingUri;
15929            this.referrer = referrer;
15930            this.originatingUid = originatingUid;
15931            this.installerUid = installerUid;
15932        }
15933    }
15934
15935    class InstallParams extends HandlerParams {
15936        final OriginInfo origin;
15937        final MoveInfo move;
15938        final IPackageInstallObserver2 observer;
15939        int installFlags;
15940        final String installerPackageName;
15941        final String volumeUuid;
15942        private InstallArgs mArgs;
15943        private int mRet;
15944        final String packageAbiOverride;
15945        final String[] grantedRuntimePermissions;
15946        final VerificationInfo verificationInfo;
15947        final Certificate[][] certificates;
15948        final int installReason;
15949
15950        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15951                int installFlags, String installerPackageName, String volumeUuid,
15952                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15953                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15954            super(user);
15955            this.origin = origin;
15956            this.move = move;
15957            this.observer = observer;
15958            this.installFlags = installFlags;
15959            this.installerPackageName = installerPackageName;
15960            this.volumeUuid = volumeUuid;
15961            this.verificationInfo = verificationInfo;
15962            this.packageAbiOverride = packageAbiOverride;
15963            this.grantedRuntimePermissions = grantedPermissions;
15964            this.certificates = certificates;
15965            this.installReason = installReason;
15966        }
15967
15968        @Override
15969        public String toString() {
15970            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15971                    + " file=" + origin.file + " cid=" + origin.cid + "}";
15972        }
15973
15974        private int installLocationPolicy(PackageInfoLite pkgLite) {
15975            String packageName = pkgLite.packageName;
15976            int installLocation = pkgLite.installLocation;
15977            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15978            // reader
15979            synchronized (mPackages) {
15980                // Currently installed package which the new package is attempting to replace or
15981                // null if no such package is installed.
15982                PackageParser.Package installedPkg = mPackages.get(packageName);
15983                // Package which currently owns the data which the new package will own if installed.
15984                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15985                // will be null whereas dataOwnerPkg will contain information about the package
15986                // which was uninstalled while keeping its data.
15987                PackageParser.Package dataOwnerPkg = installedPkg;
15988                if (dataOwnerPkg  == null) {
15989                    PackageSetting ps = mSettings.mPackages.get(packageName);
15990                    if (ps != null) {
15991                        dataOwnerPkg = ps.pkg;
15992                    }
15993                }
15994
15995                if (dataOwnerPkg != null) {
15996                    // If installed, the package will get access to data left on the device by its
15997                    // predecessor. As a security measure, this is permited only if this is not a
15998                    // version downgrade or if the predecessor package is marked as debuggable and
15999                    // a downgrade is explicitly requested.
16000                    //
16001                    // On debuggable platform builds, downgrades are permitted even for
16002                    // non-debuggable packages to make testing easier. Debuggable platform builds do
16003                    // not offer security guarantees and thus it's OK to disable some security
16004                    // mechanisms to make debugging/testing easier on those builds. However, even on
16005                    // debuggable builds downgrades of packages are permitted only if requested via
16006                    // installFlags. This is because we aim to keep the behavior of debuggable
16007                    // platform builds as close as possible to the behavior of non-debuggable
16008                    // platform builds.
16009                    final boolean downgradeRequested =
16010                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
16011                    final boolean packageDebuggable =
16012                                (dataOwnerPkg.applicationInfo.flags
16013                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
16014                    final boolean downgradePermitted =
16015                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
16016                    if (!downgradePermitted) {
16017                        try {
16018                            checkDowngrade(dataOwnerPkg, pkgLite);
16019                        } catch (PackageManagerException e) {
16020                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
16021                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
16022                        }
16023                    }
16024                }
16025
16026                if (installedPkg != null) {
16027                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16028                        // Check for updated system application.
16029                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16030                            if (onSd) {
16031                                Slog.w(TAG, "Cannot install update to system app on sdcard");
16032                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
16033                            }
16034                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16035                        } else {
16036                            if (onSd) {
16037                                // Install flag overrides everything.
16038                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16039                            }
16040                            // If current upgrade specifies particular preference
16041                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
16042                                // Application explicitly specified internal.
16043                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16044                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
16045                                // App explictly prefers external. Let policy decide
16046                            } else {
16047                                // Prefer previous location
16048                                if (isExternal(installedPkg)) {
16049                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16050                                }
16051                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
16052                            }
16053                        }
16054                    } else {
16055                        // Invalid install. Return error code
16056                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
16057                    }
16058                }
16059            }
16060            // All the special cases have been taken care of.
16061            // Return result based on recommended install location.
16062            if (onSd) {
16063                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
16064            }
16065            return pkgLite.recommendedInstallLocation;
16066        }
16067
16068        /*
16069         * Invoke remote method to get package information and install
16070         * location values. Override install location based on default
16071         * policy if needed and then create install arguments based
16072         * on the install location.
16073         */
16074        public void handleStartCopy() throws RemoteException {
16075            int ret = PackageManager.INSTALL_SUCCEEDED;
16076
16077            // If we're already staged, we've firmly committed to an install location
16078            if (origin.staged) {
16079                if (origin.file != null) {
16080                    installFlags |= PackageManager.INSTALL_INTERNAL;
16081                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16082                } else if (origin.cid != null) {
16083                    installFlags |= PackageManager.INSTALL_EXTERNAL;
16084                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
16085                } else {
16086                    throw new IllegalStateException("Invalid stage location");
16087                }
16088            }
16089
16090            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16091            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
16092            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16093            PackageInfoLite pkgLite = null;
16094
16095            if (onInt && onSd) {
16096                // Check if both bits are set.
16097                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
16098                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16099            } else if (onSd && ephemeral) {
16100                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
16101                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16102            } else {
16103                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
16104                        packageAbiOverride);
16105
16106                if (DEBUG_EPHEMERAL && ephemeral) {
16107                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
16108                }
16109
16110                /*
16111                 * If we have too little free space, try to free cache
16112                 * before giving up.
16113                 */
16114                if (!origin.staged && pkgLite.recommendedInstallLocation
16115                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16116                    // TODO: focus freeing disk space on the target device
16117                    final StorageManager storage = StorageManager.from(mContext);
16118                    final long lowThreshold = storage.getStorageLowBytes(
16119                            Environment.getDataDirectory());
16120
16121                    final long sizeBytes = mContainerService.calculateInstalledSize(
16122                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
16123
16124                    try {
16125                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
16126                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
16127                                installFlags, packageAbiOverride);
16128                    } catch (InstallerException e) {
16129                        Slog.w(TAG, "Failed to free cache", e);
16130                    }
16131
16132                    /*
16133                     * The cache free must have deleted the file we
16134                     * downloaded to install.
16135                     *
16136                     * TODO: fix the "freeCache" call to not delete
16137                     *       the file we care about.
16138                     */
16139                    if (pkgLite.recommendedInstallLocation
16140                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16141                        pkgLite.recommendedInstallLocation
16142                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
16143                    }
16144                }
16145            }
16146
16147            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16148                int loc = pkgLite.recommendedInstallLocation;
16149                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
16150                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
16151                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
16152                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
16153                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
16154                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16155                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
16156                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
16157                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
16158                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
16159                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
16160                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
16161                } else {
16162                    // Override with defaults if needed.
16163                    loc = installLocationPolicy(pkgLite);
16164                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
16165                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
16166                    } else if (!onSd && !onInt) {
16167                        // Override install location with flags
16168                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
16169                            // Set the flag to install on external media.
16170                            installFlags |= PackageManager.INSTALL_EXTERNAL;
16171                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
16172                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
16173                            if (DEBUG_EPHEMERAL) {
16174                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
16175                            }
16176                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
16177                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
16178                                    |PackageManager.INSTALL_INTERNAL);
16179                        } else {
16180                            // Make sure the flag for installing on external
16181                            // media is unset
16182                            installFlags |= PackageManager.INSTALL_INTERNAL;
16183                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
16184                        }
16185                    }
16186                }
16187            }
16188
16189            final InstallArgs args = createInstallArgs(this);
16190            mArgs = args;
16191
16192            if (ret == PackageManager.INSTALL_SUCCEEDED) {
16193                // TODO: http://b/22976637
16194                // Apps installed for "all" users use the device owner to verify the app
16195                UserHandle verifierUser = getUser();
16196                if (verifierUser == UserHandle.ALL) {
16197                    verifierUser = UserHandle.SYSTEM;
16198                }
16199
16200                /*
16201                 * Determine if we have any installed package verifiers. If we
16202                 * do, then we'll defer to them to verify the packages.
16203                 */
16204                final int requiredUid = mRequiredVerifierPackage == null ? -1
16205                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16206                                verifierUser.getIdentifier());
16207                final int installerUid =
16208                        verificationInfo == null ? -1 : verificationInfo.installerUid;
16209                if (!origin.existing && requiredUid != -1
16210                        && isVerificationEnabled(
16211                                verifierUser.getIdentifier(), installFlags, installerUid)) {
16212                    final Intent verification = new Intent(
16213                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
16214                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
16215                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
16216                            PACKAGE_MIME_TYPE);
16217                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
16218
16219                    // Query all live verifiers based on current user state
16220                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
16221                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
16222
16223                    if (DEBUG_VERIFY) {
16224                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
16225                                + verification.toString() + " with " + pkgLite.verifiers.length
16226                                + " optional verifiers");
16227                    }
16228
16229                    final int verificationId = mPendingVerificationToken++;
16230
16231                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
16232
16233                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
16234                            installerPackageName);
16235
16236                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
16237                            installFlags);
16238
16239                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
16240                            pkgLite.packageName);
16241
16242                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
16243                            pkgLite.versionCode);
16244
16245                    if (verificationInfo != null) {
16246                        if (verificationInfo.originatingUri != null) {
16247                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
16248                                    verificationInfo.originatingUri);
16249                        }
16250                        if (verificationInfo.referrer != null) {
16251                            verification.putExtra(Intent.EXTRA_REFERRER,
16252                                    verificationInfo.referrer);
16253                        }
16254                        if (verificationInfo.originatingUid >= 0) {
16255                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
16256                                    verificationInfo.originatingUid);
16257                        }
16258                        if (verificationInfo.installerUid >= 0) {
16259                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
16260                                    verificationInfo.installerUid);
16261                        }
16262                    }
16263
16264                    final PackageVerificationState verificationState = new PackageVerificationState(
16265                            requiredUid, args);
16266
16267                    mPendingVerification.append(verificationId, verificationState);
16268
16269                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
16270                            receivers, verificationState);
16271
16272                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
16273                    final long idleDuration = getVerificationTimeout();
16274
16275                    /*
16276                     * If any sufficient verifiers were listed in the package
16277                     * manifest, attempt to ask them.
16278                     */
16279                    if (sufficientVerifiers != null) {
16280                        final int N = sufficientVerifiers.size();
16281                        if (N == 0) {
16282                            Slog.i(TAG, "Additional verifiers required, but none installed.");
16283                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
16284                        } else {
16285                            for (int i = 0; i < N; i++) {
16286                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
16287                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16288                                        verifierComponent.getPackageName(), idleDuration,
16289                                        verifierUser.getIdentifier(), false, "package verifier");
16290
16291                                final Intent sufficientIntent = new Intent(verification);
16292                                sufficientIntent.setComponent(verifierComponent);
16293                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
16294                            }
16295                        }
16296                    }
16297
16298                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
16299                            mRequiredVerifierPackage, receivers);
16300                    if (ret == PackageManager.INSTALL_SUCCEEDED
16301                            && mRequiredVerifierPackage != null) {
16302                        Trace.asyncTraceBegin(
16303                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
16304                        /*
16305                         * Send the intent to the required verification agent,
16306                         * but only start the verification timeout after the
16307                         * target BroadcastReceivers have run.
16308                         */
16309                        verification.setComponent(requiredVerifierComponent);
16310                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
16311                                mRequiredVerifierPackage, idleDuration,
16312                                verifierUser.getIdentifier(), false, "package verifier");
16313                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
16314                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16315                                new BroadcastReceiver() {
16316                                    @Override
16317                                    public void onReceive(Context context, Intent intent) {
16318                                        final Message msg = mHandler
16319                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
16320                                        msg.arg1 = verificationId;
16321                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
16322                                    }
16323                                }, null, 0, null, null);
16324
16325                        /*
16326                         * We don't want the copy to proceed until verification
16327                         * succeeds, so null out this field.
16328                         */
16329                        mArgs = null;
16330                    }
16331                } else {
16332                    /*
16333                     * No package verification is enabled, so immediately start
16334                     * the remote call to initiate copy using temporary file.
16335                     */
16336                    ret = args.copyApk(mContainerService, true);
16337                }
16338            }
16339
16340            mRet = ret;
16341        }
16342
16343        @Override
16344        void handleReturnCode() {
16345            // If mArgs is null, then MCS couldn't be reached. When it
16346            // reconnects, it will try again to install. At that point, this
16347            // will succeed.
16348            if (mArgs != null) {
16349                processPendingInstall(mArgs, mRet);
16350            }
16351        }
16352
16353        @Override
16354        void handleServiceError() {
16355            mArgs = createInstallArgs(this);
16356            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16357        }
16358
16359        public boolean isForwardLocked() {
16360            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16361        }
16362    }
16363
16364    /**
16365     * Used during creation of InstallArgs
16366     *
16367     * @param installFlags package installation flags
16368     * @return true if should be installed on external storage
16369     */
16370    private static boolean installOnExternalAsec(int installFlags) {
16371        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16372            return false;
16373        }
16374        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16375            return true;
16376        }
16377        return false;
16378    }
16379
16380    /**
16381     * Used during creation of InstallArgs
16382     *
16383     * @param installFlags package installation flags
16384     * @return true if should be installed as forward locked
16385     */
16386    private static boolean installForwardLocked(int installFlags) {
16387        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16388    }
16389
16390    private InstallArgs createInstallArgs(InstallParams params) {
16391        if (params.move != null) {
16392            return new MoveInstallArgs(params);
16393        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16394            return new AsecInstallArgs(params);
16395        } else {
16396            return new FileInstallArgs(params);
16397        }
16398    }
16399
16400    /**
16401     * Create args that describe an existing installed package. Typically used
16402     * when cleaning up old installs, or used as a move source.
16403     */
16404    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16405            String resourcePath, String[] instructionSets) {
16406        final boolean isInAsec;
16407        if (installOnExternalAsec(installFlags)) {
16408            /* Apps on SD card are always in ASEC containers. */
16409            isInAsec = true;
16410        } else if (installForwardLocked(installFlags)
16411                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16412            /*
16413             * Forward-locked apps are only in ASEC containers if they're the
16414             * new style
16415             */
16416            isInAsec = true;
16417        } else {
16418            isInAsec = false;
16419        }
16420
16421        if (isInAsec) {
16422            return new AsecInstallArgs(codePath, instructionSets,
16423                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16424        } else {
16425            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16426        }
16427    }
16428
16429    static abstract class InstallArgs {
16430        /** @see InstallParams#origin */
16431        final OriginInfo origin;
16432        /** @see InstallParams#move */
16433        final MoveInfo move;
16434
16435        final IPackageInstallObserver2 observer;
16436        // Always refers to PackageManager flags only
16437        final int installFlags;
16438        final String installerPackageName;
16439        final String volumeUuid;
16440        final UserHandle user;
16441        final String abiOverride;
16442        final String[] installGrantPermissions;
16443        /** If non-null, drop an async trace when the install completes */
16444        final String traceMethod;
16445        final int traceCookie;
16446        final Certificate[][] certificates;
16447        final int installReason;
16448
16449        // The list of instruction sets supported by this app. This is currently
16450        // only used during the rmdex() phase to clean up resources. We can get rid of this
16451        // if we move dex files under the common app path.
16452        /* nullable */ String[] instructionSets;
16453
16454        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16455                int installFlags, String installerPackageName, String volumeUuid,
16456                UserHandle user, String[] instructionSets,
16457                String abiOverride, String[] installGrantPermissions,
16458                String traceMethod, int traceCookie, Certificate[][] certificates,
16459                int installReason) {
16460            this.origin = origin;
16461            this.move = move;
16462            this.installFlags = installFlags;
16463            this.observer = observer;
16464            this.installerPackageName = installerPackageName;
16465            this.volumeUuid = volumeUuid;
16466            this.user = user;
16467            this.instructionSets = instructionSets;
16468            this.abiOverride = abiOverride;
16469            this.installGrantPermissions = installGrantPermissions;
16470            this.traceMethod = traceMethod;
16471            this.traceCookie = traceCookie;
16472            this.certificates = certificates;
16473            this.installReason = installReason;
16474        }
16475
16476        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16477        abstract int doPreInstall(int status);
16478
16479        /**
16480         * Rename package into final resting place. All paths on the given
16481         * scanned package should be updated to reflect the rename.
16482         */
16483        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16484        abstract int doPostInstall(int status, int uid);
16485
16486        /** @see PackageSettingBase#codePathString */
16487        abstract String getCodePath();
16488        /** @see PackageSettingBase#resourcePathString */
16489        abstract String getResourcePath();
16490
16491        // Need installer lock especially for dex file removal.
16492        abstract void cleanUpResourcesLI();
16493        abstract boolean doPostDeleteLI(boolean delete);
16494
16495        /**
16496         * Called before the source arguments are copied. This is used mostly
16497         * for MoveParams when it needs to read the source file to put it in the
16498         * destination.
16499         */
16500        int doPreCopy() {
16501            return PackageManager.INSTALL_SUCCEEDED;
16502        }
16503
16504        /**
16505         * Called after the source arguments are copied. This is used mostly for
16506         * MoveParams when it needs to read the source file to put it in the
16507         * destination.
16508         */
16509        int doPostCopy(int uid) {
16510            return PackageManager.INSTALL_SUCCEEDED;
16511        }
16512
16513        protected boolean isFwdLocked() {
16514            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16515        }
16516
16517        protected boolean isExternalAsec() {
16518            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16519        }
16520
16521        protected boolean isEphemeral() {
16522            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16523        }
16524
16525        UserHandle getUser() {
16526            return user;
16527        }
16528    }
16529
16530    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16531        if (!allCodePaths.isEmpty()) {
16532            if (instructionSets == null) {
16533                throw new IllegalStateException("instructionSet == null");
16534            }
16535            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16536            for (String codePath : allCodePaths) {
16537                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16538                    try {
16539                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16540                    } catch (InstallerException ignored) {
16541                    }
16542                }
16543            }
16544        }
16545    }
16546
16547    /**
16548     * Logic to handle installation of non-ASEC applications, including copying
16549     * and renaming logic.
16550     */
16551    class FileInstallArgs extends InstallArgs {
16552        private File codeFile;
16553        private File resourceFile;
16554
16555        // Example topology:
16556        // /data/app/com.example/base.apk
16557        // /data/app/com.example/split_foo.apk
16558        // /data/app/com.example/lib/arm/libfoo.so
16559        // /data/app/com.example/lib/arm64/libfoo.so
16560        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16561
16562        /** New install */
16563        FileInstallArgs(InstallParams params) {
16564            super(params.origin, params.move, params.observer, params.installFlags,
16565                    params.installerPackageName, params.volumeUuid,
16566                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16567                    params.grantedRuntimePermissions,
16568                    params.traceMethod, params.traceCookie, params.certificates,
16569                    params.installReason);
16570            if (isFwdLocked()) {
16571                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16572            }
16573        }
16574
16575        /** Existing install */
16576        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16577            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16578                    null, null, null, 0, null /*certificates*/,
16579                    PackageManager.INSTALL_REASON_UNKNOWN);
16580            this.codeFile = (codePath != null) ? new File(codePath) : null;
16581            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16582        }
16583
16584        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16585            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16586            try {
16587                return doCopyApk(imcs, temp);
16588            } finally {
16589                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16590            }
16591        }
16592
16593        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16594            if (origin.staged) {
16595                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16596                codeFile = origin.file;
16597                resourceFile = origin.file;
16598                return PackageManager.INSTALL_SUCCEEDED;
16599            }
16600
16601            try {
16602                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16603                final File tempDir =
16604                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16605                codeFile = tempDir;
16606                resourceFile = tempDir;
16607            } catch (IOException e) {
16608                Slog.w(TAG, "Failed to create copy file: " + e);
16609                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16610            }
16611
16612            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16613                @Override
16614                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16615                    if (!FileUtils.isValidExtFilename(name)) {
16616                        throw new IllegalArgumentException("Invalid filename: " + name);
16617                    }
16618                    try {
16619                        final File file = new File(codeFile, name);
16620                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16621                                O_RDWR | O_CREAT, 0644);
16622                        Os.chmod(file.getAbsolutePath(), 0644);
16623                        return new ParcelFileDescriptor(fd);
16624                    } catch (ErrnoException e) {
16625                        throw new RemoteException("Failed to open: " + e.getMessage());
16626                    }
16627                }
16628            };
16629
16630            int ret = PackageManager.INSTALL_SUCCEEDED;
16631            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16632            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16633                Slog.e(TAG, "Failed to copy package");
16634                return ret;
16635            }
16636
16637            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16638            NativeLibraryHelper.Handle handle = null;
16639            try {
16640                handle = NativeLibraryHelper.Handle.create(codeFile);
16641                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16642                        abiOverride);
16643            } catch (IOException e) {
16644                Slog.e(TAG, "Copying native libraries failed", e);
16645                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16646            } finally {
16647                IoUtils.closeQuietly(handle);
16648            }
16649
16650            return ret;
16651        }
16652
16653        int doPreInstall(int status) {
16654            if (status != PackageManager.INSTALL_SUCCEEDED) {
16655                cleanUp();
16656            }
16657            return status;
16658        }
16659
16660        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16661            if (status != PackageManager.INSTALL_SUCCEEDED) {
16662                cleanUp();
16663                return false;
16664            }
16665
16666            final File targetDir = codeFile.getParentFile();
16667            final File beforeCodeFile = codeFile;
16668            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16669
16670            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16671            try {
16672                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16673            } catch (ErrnoException e) {
16674                Slog.w(TAG, "Failed to rename", e);
16675                return false;
16676            }
16677
16678            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16679                Slog.w(TAG, "Failed to restorecon");
16680                return false;
16681            }
16682
16683            // Reflect the rename internally
16684            codeFile = afterCodeFile;
16685            resourceFile = afterCodeFile;
16686
16687            // Reflect the rename in scanned details
16688            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16689            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16690                    afterCodeFile, pkg.baseCodePath));
16691            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16692                    afterCodeFile, pkg.splitCodePaths));
16693
16694            // Reflect the rename in app info
16695            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16696            pkg.setApplicationInfoCodePath(pkg.codePath);
16697            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16698            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16699            pkg.setApplicationInfoResourcePath(pkg.codePath);
16700            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16701            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16702
16703            return true;
16704        }
16705
16706        int doPostInstall(int status, int uid) {
16707            if (status != PackageManager.INSTALL_SUCCEEDED) {
16708                cleanUp();
16709            }
16710            return status;
16711        }
16712
16713        @Override
16714        String getCodePath() {
16715            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16716        }
16717
16718        @Override
16719        String getResourcePath() {
16720            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16721        }
16722
16723        private boolean cleanUp() {
16724            if (codeFile == null || !codeFile.exists()) {
16725                return false;
16726            }
16727
16728            removeCodePathLI(codeFile);
16729
16730            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16731                resourceFile.delete();
16732            }
16733
16734            return true;
16735        }
16736
16737        void cleanUpResourcesLI() {
16738            // Try enumerating all code paths before deleting
16739            List<String> allCodePaths = Collections.EMPTY_LIST;
16740            if (codeFile != null && codeFile.exists()) {
16741                try {
16742                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16743                    allCodePaths = pkg.getAllCodePaths();
16744                } catch (PackageParserException e) {
16745                    // Ignored; we tried our best
16746                }
16747            }
16748
16749            cleanUp();
16750            removeDexFiles(allCodePaths, instructionSets);
16751        }
16752
16753        boolean doPostDeleteLI(boolean delete) {
16754            // XXX err, shouldn't we respect the delete flag?
16755            cleanUpResourcesLI();
16756            return true;
16757        }
16758    }
16759
16760    private boolean isAsecExternal(String cid) {
16761        final String asecPath = PackageHelper.getSdFilesystem(cid);
16762        return !asecPath.startsWith(mAsecInternalPath);
16763    }
16764
16765    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16766            PackageManagerException {
16767        if (copyRet < 0) {
16768            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16769                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16770                throw new PackageManagerException(copyRet, message);
16771            }
16772        }
16773    }
16774
16775    /**
16776     * Extract the StorageManagerService "container ID" from the full code path of an
16777     * .apk.
16778     */
16779    static String cidFromCodePath(String fullCodePath) {
16780        int eidx = fullCodePath.lastIndexOf("/");
16781        String subStr1 = fullCodePath.substring(0, eidx);
16782        int sidx = subStr1.lastIndexOf("/");
16783        return subStr1.substring(sidx+1, eidx);
16784    }
16785
16786    /**
16787     * Logic to handle installation of ASEC applications, including copying and
16788     * renaming logic.
16789     */
16790    class AsecInstallArgs extends InstallArgs {
16791        static final String RES_FILE_NAME = "pkg.apk";
16792        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16793
16794        String cid;
16795        String packagePath;
16796        String resourcePath;
16797
16798        /** New install */
16799        AsecInstallArgs(InstallParams params) {
16800            super(params.origin, params.move, params.observer, params.installFlags,
16801                    params.installerPackageName, params.volumeUuid,
16802                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16803                    params.grantedRuntimePermissions,
16804                    params.traceMethod, params.traceCookie, params.certificates,
16805                    params.installReason);
16806        }
16807
16808        /** Existing install */
16809        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16810                        boolean isExternal, boolean isForwardLocked) {
16811            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16812                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16813                    instructionSets, null, null, null, 0, null /*certificates*/,
16814                    PackageManager.INSTALL_REASON_UNKNOWN);
16815            // Hackily pretend we're still looking at a full code path
16816            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16817                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16818            }
16819
16820            // Extract cid from fullCodePath
16821            int eidx = fullCodePath.lastIndexOf("/");
16822            String subStr1 = fullCodePath.substring(0, eidx);
16823            int sidx = subStr1.lastIndexOf("/");
16824            cid = subStr1.substring(sidx+1, eidx);
16825            setMountPath(subStr1);
16826        }
16827
16828        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16829            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16830                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16831                    instructionSets, null, null, null, 0, null /*certificates*/,
16832                    PackageManager.INSTALL_REASON_UNKNOWN);
16833            this.cid = cid;
16834            setMountPath(PackageHelper.getSdDir(cid));
16835        }
16836
16837        void createCopyFile() {
16838            cid = mInstallerService.allocateExternalStageCidLegacy();
16839        }
16840
16841        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16842            if (origin.staged && origin.cid != null) {
16843                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16844                cid = origin.cid;
16845                setMountPath(PackageHelper.getSdDir(cid));
16846                return PackageManager.INSTALL_SUCCEEDED;
16847            }
16848
16849            if (temp) {
16850                createCopyFile();
16851            } else {
16852                /*
16853                 * Pre-emptively destroy the container since it's destroyed if
16854                 * copying fails due to it existing anyway.
16855                 */
16856                PackageHelper.destroySdDir(cid);
16857            }
16858
16859            final String newMountPath = imcs.copyPackageToContainer(
16860                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16861                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16862
16863            if (newMountPath != null) {
16864                setMountPath(newMountPath);
16865                return PackageManager.INSTALL_SUCCEEDED;
16866            } else {
16867                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16868            }
16869        }
16870
16871        @Override
16872        String getCodePath() {
16873            return packagePath;
16874        }
16875
16876        @Override
16877        String getResourcePath() {
16878            return resourcePath;
16879        }
16880
16881        int doPreInstall(int status) {
16882            if (status != PackageManager.INSTALL_SUCCEEDED) {
16883                // Destroy container
16884                PackageHelper.destroySdDir(cid);
16885            } else {
16886                boolean mounted = PackageHelper.isContainerMounted(cid);
16887                if (!mounted) {
16888                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16889                            Process.SYSTEM_UID);
16890                    if (newMountPath != null) {
16891                        setMountPath(newMountPath);
16892                    } else {
16893                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16894                    }
16895                }
16896            }
16897            return status;
16898        }
16899
16900        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16901            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16902            String newMountPath = null;
16903            if (PackageHelper.isContainerMounted(cid)) {
16904                // Unmount the container
16905                if (!PackageHelper.unMountSdDir(cid)) {
16906                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16907                    return false;
16908                }
16909            }
16910            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16911                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16912                        " which might be stale. Will try to clean up.");
16913                // Clean up the stale container and proceed to recreate.
16914                if (!PackageHelper.destroySdDir(newCacheId)) {
16915                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16916                    return false;
16917                }
16918                // Successfully cleaned up stale container. Try to rename again.
16919                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16920                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16921                            + " inspite of cleaning it up.");
16922                    return false;
16923                }
16924            }
16925            if (!PackageHelper.isContainerMounted(newCacheId)) {
16926                Slog.w(TAG, "Mounting container " + newCacheId);
16927                newMountPath = PackageHelper.mountSdDir(newCacheId,
16928                        getEncryptKey(), Process.SYSTEM_UID);
16929            } else {
16930                newMountPath = PackageHelper.getSdDir(newCacheId);
16931            }
16932            if (newMountPath == null) {
16933                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16934                return false;
16935            }
16936            Log.i(TAG, "Succesfully renamed " + cid +
16937                    " to " + newCacheId +
16938                    " at new path: " + newMountPath);
16939            cid = newCacheId;
16940
16941            final File beforeCodeFile = new File(packagePath);
16942            setMountPath(newMountPath);
16943            final File afterCodeFile = new File(packagePath);
16944
16945            // Reflect the rename in scanned details
16946            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16947            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16948                    afterCodeFile, pkg.baseCodePath));
16949            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16950                    afterCodeFile, pkg.splitCodePaths));
16951
16952            // Reflect the rename in app info
16953            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16954            pkg.setApplicationInfoCodePath(pkg.codePath);
16955            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16956            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16957            pkg.setApplicationInfoResourcePath(pkg.codePath);
16958            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16959            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16960
16961            return true;
16962        }
16963
16964        private void setMountPath(String mountPath) {
16965            final File mountFile = new File(mountPath);
16966
16967            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16968            if (monolithicFile.exists()) {
16969                packagePath = monolithicFile.getAbsolutePath();
16970                if (isFwdLocked()) {
16971                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16972                } else {
16973                    resourcePath = packagePath;
16974                }
16975            } else {
16976                packagePath = mountFile.getAbsolutePath();
16977                resourcePath = packagePath;
16978            }
16979        }
16980
16981        int doPostInstall(int status, int uid) {
16982            if (status != PackageManager.INSTALL_SUCCEEDED) {
16983                cleanUp();
16984            } else {
16985                final int groupOwner;
16986                final String protectedFile;
16987                if (isFwdLocked()) {
16988                    groupOwner = UserHandle.getSharedAppGid(uid);
16989                    protectedFile = RES_FILE_NAME;
16990                } else {
16991                    groupOwner = -1;
16992                    protectedFile = null;
16993                }
16994
16995                if (uid < Process.FIRST_APPLICATION_UID
16996                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16997                    Slog.e(TAG, "Failed to finalize " + cid);
16998                    PackageHelper.destroySdDir(cid);
16999                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17000                }
17001
17002                boolean mounted = PackageHelper.isContainerMounted(cid);
17003                if (!mounted) {
17004                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
17005                }
17006            }
17007            return status;
17008        }
17009
17010        private void cleanUp() {
17011            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
17012
17013            // Destroy secure container
17014            PackageHelper.destroySdDir(cid);
17015        }
17016
17017        private List<String> getAllCodePaths() {
17018            final File codeFile = new File(getCodePath());
17019            if (codeFile != null && codeFile.exists()) {
17020                try {
17021                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
17022                    return pkg.getAllCodePaths();
17023                } catch (PackageParserException e) {
17024                    // Ignored; we tried our best
17025                }
17026            }
17027            return Collections.EMPTY_LIST;
17028        }
17029
17030        void cleanUpResourcesLI() {
17031            // Enumerate all code paths before deleting
17032            cleanUpResourcesLI(getAllCodePaths());
17033        }
17034
17035        private void cleanUpResourcesLI(List<String> allCodePaths) {
17036            cleanUp();
17037            removeDexFiles(allCodePaths, instructionSets);
17038        }
17039
17040        String getPackageName() {
17041            return getAsecPackageName(cid);
17042        }
17043
17044        boolean doPostDeleteLI(boolean delete) {
17045            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
17046            final List<String> allCodePaths = getAllCodePaths();
17047            boolean mounted = PackageHelper.isContainerMounted(cid);
17048            if (mounted) {
17049                // Unmount first
17050                if (PackageHelper.unMountSdDir(cid)) {
17051                    mounted = false;
17052                }
17053            }
17054            if (!mounted && delete) {
17055                cleanUpResourcesLI(allCodePaths);
17056            }
17057            return !mounted;
17058        }
17059
17060        @Override
17061        int doPreCopy() {
17062            if (isFwdLocked()) {
17063                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
17064                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
17065                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17066                }
17067            }
17068
17069            return PackageManager.INSTALL_SUCCEEDED;
17070        }
17071
17072        @Override
17073        int doPostCopy(int uid) {
17074            if (isFwdLocked()) {
17075                if (uid < Process.FIRST_APPLICATION_UID
17076                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
17077                                RES_FILE_NAME)) {
17078                    Slog.e(TAG, "Failed to finalize " + cid);
17079                    PackageHelper.destroySdDir(cid);
17080                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17081                }
17082            }
17083
17084            return PackageManager.INSTALL_SUCCEEDED;
17085        }
17086    }
17087
17088    /**
17089     * Logic to handle movement of existing installed applications.
17090     */
17091    class MoveInstallArgs extends InstallArgs {
17092        private File codeFile;
17093        private File resourceFile;
17094
17095        /** New install */
17096        MoveInstallArgs(InstallParams params) {
17097            super(params.origin, params.move, params.observer, params.installFlags,
17098                    params.installerPackageName, params.volumeUuid,
17099                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
17100                    params.grantedRuntimePermissions,
17101                    params.traceMethod, params.traceCookie, params.certificates,
17102                    params.installReason);
17103        }
17104
17105        int copyApk(IMediaContainerService imcs, boolean temp) {
17106            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
17107                    + move.fromUuid + " to " + move.toUuid);
17108            synchronized (mInstaller) {
17109                try {
17110                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
17111                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
17112                } catch (InstallerException e) {
17113                    Slog.w(TAG, "Failed to move app", e);
17114                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
17115                }
17116            }
17117
17118            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
17119            resourceFile = codeFile;
17120            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
17121
17122            return PackageManager.INSTALL_SUCCEEDED;
17123        }
17124
17125        int doPreInstall(int status) {
17126            if (status != PackageManager.INSTALL_SUCCEEDED) {
17127                cleanUp(move.toUuid);
17128            }
17129            return status;
17130        }
17131
17132        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
17133            if (status != PackageManager.INSTALL_SUCCEEDED) {
17134                cleanUp(move.toUuid);
17135                return false;
17136            }
17137
17138            // Reflect the move in app info
17139            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
17140            pkg.setApplicationInfoCodePath(pkg.codePath);
17141            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
17142            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
17143            pkg.setApplicationInfoResourcePath(pkg.codePath);
17144            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
17145            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
17146
17147            return true;
17148        }
17149
17150        int doPostInstall(int status, int uid) {
17151            if (status == PackageManager.INSTALL_SUCCEEDED) {
17152                cleanUp(move.fromUuid);
17153            } else {
17154                cleanUp(move.toUuid);
17155            }
17156            return status;
17157        }
17158
17159        @Override
17160        String getCodePath() {
17161            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
17162        }
17163
17164        @Override
17165        String getResourcePath() {
17166            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
17167        }
17168
17169        private boolean cleanUp(String volumeUuid) {
17170            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
17171                    move.dataAppName);
17172            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
17173            final int[] userIds = sUserManager.getUserIds();
17174            synchronized (mInstallLock) {
17175                // Clean up both app data and code
17176                // All package moves are frozen until finished
17177                for (int userId : userIds) {
17178                    try {
17179                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
17180                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
17181                    } catch (InstallerException e) {
17182                        Slog.w(TAG, String.valueOf(e));
17183                    }
17184                }
17185                removeCodePathLI(codeFile);
17186            }
17187            return true;
17188        }
17189
17190        void cleanUpResourcesLI() {
17191            throw new UnsupportedOperationException();
17192        }
17193
17194        boolean doPostDeleteLI(boolean delete) {
17195            throw new UnsupportedOperationException();
17196        }
17197    }
17198
17199    static String getAsecPackageName(String packageCid) {
17200        int idx = packageCid.lastIndexOf("-");
17201        if (idx == -1) {
17202            return packageCid;
17203        }
17204        return packageCid.substring(0, idx);
17205    }
17206
17207    // Utility method used to create code paths based on package name and available index.
17208    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
17209        String idxStr = "";
17210        int idx = 1;
17211        // Fall back to default value of idx=1 if prefix is not
17212        // part of oldCodePath
17213        if (oldCodePath != null) {
17214            String subStr = oldCodePath;
17215            // Drop the suffix right away
17216            if (suffix != null && subStr.endsWith(suffix)) {
17217                subStr = subStr.substring(0, subStr.length() - suffix.length());
17218            }
17219            // If oldCodePath already contains prefix find out the
17220            // ending index to either increment or decrement.
17221            int sidx = subStr.lastIndexOf(prefix);
17222            if (sidx != -1) {
17223                subStr = subStr.substring(sidx + prefix.length());
17224                if (subStr != null) {
17225                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
17226                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
17227                    }
17228                    try {
17229                        idx = Integer.parseInt(subStr);
17230                        if (idx <= 1) {
17231                            idx++;
17232                        } else {
17233                            idx--;
17234                        }
17235                    } catch(NumberFormatException e) {
17236                    }
17237                }
17238            }
17239        }
17240        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
17241        return prefix + idxStr;
17242    }
17243
17244    private File getNextCodePath(File targetDir, String packageName) {
17245        File result;
17246        SecureRandom random = new SecureRandom();
17247        byte[] bytes = new byte[16];
17248        do {
17249            random.nextBytes(bytes);
17250            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
17251            result = new File(targetDir, packageName + "-" + suffix);
17252        } while (result.exists());
17253        return result;
17254    }
17255
17256    // Utility method that returns the relative package path with respect
17257    // to the installation directory. Like say for /data/data/com.test-1.apk
17258    // string com.test-1 is returned.
17259    static String deriveCodePathName(String codePath) {
17260        if (codePath == null) {
17261            return null;
17262        }
17263        final File codeFile = new File(codePath);
17264        final String name = codeFile.getName();
17265        if (codeFile.isDirectory()) {
17266            return name;
17267        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
17268            final int lastDot = name.lastIndexOf('.');
17269            return name.substring(0, lastDot);
17270        } else {
17271            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
17272            return null;
17273        }
17274    }
17275
17276    static class PackageInstalledInfo {
17277        String name;
17278        int uid;
17279        // The set of users that originally had this package installed.
17280        int[] origUsers;
17281        // The set of users that now have this package installed.
17282        int[] newUsers;
17283        PackageParser.Package pkg;
17284        int returnCode;
17285        String returnMsg;
17286        PackageRemovedInfo removedInfo;
17287        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
17288
17289        public void setError(int code, String msg) {
17290            setReturnCode(code);
17291            setReturnMessage(msg);
17292            Slog.w(TAG, msg);
17293        }
17294
17295        public void setError(String msg, PackageParserException e) {
17296            setReturnCode(e.error);
17297            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17298            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17299            for (int i = 0; i < childCount; i++) {
17300                addedChildPackages.valueAt(i).setError(msg, e);
17301            }
17302            Slog.w(TAG, msg, e);
17303        }
17304
17305        public void setError(String msg, PackageManagerException e) {
17306            returnCode = e.error;
17307            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
17308            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17309            for (int i = 0; i < childCount; i++) {
17310                addedChildPackages.valueAt(i).setError(msg, e);
17311            }
17312            Slog.w(TAG, msg, e);
17313        }
17314
17315        public void setReturnCode(int returnCode) {
17316            this.returnCode = returnCode;
17317            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17318            for (int i = 0; i < childCount; i++) {
17319                addedChildPackages.valueAt(i).returnCode = returnCode;
17320            }
17321        }
17322
17323        private void setReturnMessage(String returnMsg) {
17324            this.returnMsg = returnMsg;
17325            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
17326            for (int i = 0; i < childCount; i++) {
17327                addedChildPackages.valueAt(i).returnMsg = returnMsg;
17328            }
17329        }
17330
17331        // In some error cases we want to convey more info back to the observer
17332        String origPackage;
17333        String origPermission;
17334    }
17335
17336    /*
17337     * Install a non-existing package.
17338     */
17339    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17340            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17341            PackageInstalledInfo res, int installReason) {
17342        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17343
17344        // Remember this for later, in case we need to rollback this install
17345        String pkgName = pkg.packageName;
17346
17347        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17348
17349        synchronized(mPackages) {
17350            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17351            if (renamedPackage != null) {
17352                // A package with the same name is already installed, though
17353                // it has been renamed to an older name.  The package we
17354                // are trying to install should be installed as an update to
17355                // the existing one, but that has not been requested, so bail.
17356                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17357                        + " without first uninstalling package running as "
17358                        + renamedPackage);
17359                return;
17360            }
17361            if (mPackages.containsKey(pkgName)) {
17362                // Don't allow installation over an existing package with the same name.
17363                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17364                        + " without first uninstalling.");
17365                return;
17366            }
17367        }
17368
17369        try {
17370            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17371                    System.currentTimeMillis(), user);
17372
17373            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17374
17375            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17376                prepareAppDataAfterInstallLIF(newPackage);
17377
17378            } else {
17379                // Remove package from internal structures, but keep around any
17380                // data that might have already existed
17381                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17382                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17383            }
17384        } catch (PackageManagerException e) {
17385            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17386        }
17387
17388        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17389    }
17390
17391    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17392        // Can't rotate keys during boot or if sharedUser.
17393        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17394                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17395            return false;
17396        }
17397        // app is using upgradeKeySets; make sure all are valid
17398        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17399        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17400        for (int i = 0; i < upgradeKeySets.length; i++) {
17401            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17402                Slog.wtf(TAG, "Package "
17403                         + (oldPs.name != null ? oldPs.name : "<null>")
17404                         + " contains upgrade-key-set reference to unknown key-set: "
17405                         + upgradeKeySets[i]
17406                         + " reverting to signatures check.");
17407                return false;
17408            }
17409        }
17410        return true;
17411    }
17412
17413    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17414        // Upgrade keysets are being used.  Determine if new package has a superset of the
17415        // required keys.
17416        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17417        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17418        for (int i = 0; i < upgradeKeySets.length; i++) {
17419            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17420            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17421                return true;
17422            }
17423        }
17424        return false;
17425    }
17426
17427    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17428        try (DigestInputStream digestStream =
17429                new DigestInputStream(new FileInputStream(file), digest)) {
17430            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17431        }
17432    }
17433
17434    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17435            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17436            int installReason) {
17437        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17438
17439        final PackageParser.Package oldPackage;
17440        final PackageSetting ps;
17441        final String pkgName = pkg.packageName;
17442        final int[] allUsers;
17443        final int[] installedUsers;
17444
17445        synchronized(mPackages) {
17446            oldPackage = mPackages.get(pkgName);
17447            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17448
17449            // don't allow upgrade to target a release SDK from a pre-release SDK
17450            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17451                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17452            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17453                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17454            if (oldTargetsPreRelease
17455                    && !newTargetsPreRelease
17456                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17457                Slog.w(TAG, "Can't install package targeting released sdk");
17458                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17459                return;
17460            }
17461
17462            ps = mSettings.mPackages.get(pkgName);
17463
17464            // verify signatures are valid
17465            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17466                if (!checkUpgradeKeySetLP(ps, pkg)) {
17467                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17468                            "New package not signed by keys specified by upgrade-keysets: "
17469                                    + pkgName);
17470                    return;
17471                }
17472            } else {
17473                // default to original signature matching
17474                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17475                        != PackageManager.SIGNATURE_MATCH) {
17476                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17477                            "New package has a different signature: " + pkgName);
17478                    return;
17479                }
17480            }
17481
17482            // don't allow a system upgrade unless the upgrade hash matches
17483            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17484                byte[] digestBytes = null;
17485                try {
17486                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17487                    updateDigest(digest, new File(pkg.baseCodePath));
17488                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17489                        for (String path : pkg.splitCodePaths) {
17490                            updateDigest(digest, new File(path));
17491                        }
17492                    }
17493                    digestBytes = digest.digest();
17494                } catch (NoSuchAlgorithmException | IOException e) {
17495                    res.setError(INSTALL_FAILED_INVALID_APK,
17496                            "Could not compute hash: " + pkgName);
17497                    return;
17498                }
17499                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17500                    res.setError(INSTALL_FAILED_INVALID_APK,
17501                            "New package fails restrict-update check: " + pkgName);
17502                    return;
17503                }
17504                // retain upgrade restriction
17505                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17506            }
17507
17508            // Check for shared user id changes
17509            String invalidPackageName =
17510                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17511            if (invalidPackageName != null) {
17512                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17513                        "Package " + invalidPackageName + " tried to change user "
17514                                + oldPackage.mSharedUserId);
17515                return;
17516            }
17517
17518            // In case of rollback, remember per-user/profile install state
17519            allUsers = sUserManager.getUserIds();
17520            installedUsers = ps.queryInstalledUsers(allUsers, true);
17521
17522            // don't allow an upgrade from full to ephemeral
17523            if (isInstantApp) {
17524                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17525                    for (int currentUser : allUsers) {
17526                        if (!ps.getInstantApp(currentUser)) {
17527                            // can't downgrade from full to instant
17528                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17529                                    + " for user: " + currentUser);
17530                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17531                            return;
17532                        }
17533                    }
17534                } else if (!ps.getInstantApp(user.getIdentifier())) {
17535                    // can't downgrade from full to instant
17536                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17537                            + " for user: " + user.getIdentifier());
17538                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17539                    return;
17540                }
17541            }
17542        }
17543
17544        // Update what is removed
17545        res.removedInfo = new PackageRemovedInfo(this);
17546        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17547        res.removedInfo.removedPackage = oldPackage.packageName;
17548        res.removedInfo.installerPackageName = ps.installerPackageName;
17549        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17550        res.removedInfo.isUpdate = true;
17551        res.removedInfo.origUsers = installedUsers;
17552        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17553        for (int i = 0; i < installedUsers.length; i++) {
17554            final int userId = installedUsers[i];
17555            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17556        }
17557
17558        final int childCount = (oldPackage.childPackages != null)
17559                ? oldPackage.childPackages.size() : 0;
17560        for (int i = 0; i < childCount; i++) {
17561            boolean childPackageUpdated = false;
17562            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17563            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17564            if (res.addedChildPackages != null) {
17565                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17566                if (childRes != null) {
17567                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17568                    childRes.removedInfo.removedPackage = childPkg.packageName;
17569                    if (childPs != null) {
17570                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17571                    }
17572                    childRes.removedInfo.isUpdate = true;
17573                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17574                    childPackageUpdated = true;
17575                }
17576            }
17577            if (!childPackageUpdated) {
17578                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17579                childRemovedRes.removedPackage = childPkg.packageName;
17580                if (childPs != null) {
17581                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17582                }
17583                childRemovedRes.isUpdate = false;
17584                childRemovedRes.dataRemoved = true;
17585                synchronized (mPackages) {
17586                    if (childPs != null) {
17587                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17588                    }
17589                }
17590                if (res.removedInfo.removedChildPackages == null) {
17591                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17592                }
17593                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17594            }
17595        }
17596
17597        boolean sysPkg = (isSystemApp(oldPackage));
17598        if (sysPkg) {
17599            // Set the system/privileged flags as needed
17600            final boolean privileged =
17601                    (oldPackage.applicationInfo.privateFlags
17602                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17603            final int systemPolicyFlags = policyFlags
17604                    | PackageParser.PARSE_IS_SYSTEM
17605                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17606
17607            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17608                    user, allUsers, installerPackageName, res, installReason);
17609        } else {
17610            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17611                    user, allUsers, installerPackageName, res, installReason);
17612        }
17613    }
17614
17615    @Override
17616    public List<String> getPreviousCodePaths(String packageName) {
17617        final int callingUid = Binder.getCallingUid();
17618        final List<String> result = new ArrayList<>();
17619        if (getInstantAppPackageName(callingUid) != null) {
17620            return result;
17621        }
17622        final PackageSetting ps = mSettings.mPackages.get(packageName);
17623        if (ps != null
17624                && ps.oldCodePaths != null
17625                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17626            result.addAll(ps.oldCodePaths);
17627        }
17628        return result;
17629    }
17630
17631    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17632            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17633            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17634            int installReason) {
17635        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17636                + deletedPackage);
17637
17638        String pkgName = deletedPackage.packageName;
17639        boolean deletedPkg = true;
17640        boolean addedPkg = false;
17641        boolean updatedSettings = false;
17642        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17643        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17644                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17645
17646        final long origUpdateTime = (pkg.mExtras != null)
17647                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17648
17649        // First delete the existing package while retaining the data directory
17650        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17651                res.removedInfo, true, pkg)) {
17652            // If the existing package wasn't successfully deleted
17653            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17654            deletedPkg = false;
17655        } else {
17656            // Successfully deleted the old package; proceed with replace.
17657
17658            // If deleted package lived in a container, give users a chance to
17659            // relinquish resources before killing.
17660            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17661                if (DEBUG_INSTALL) {
17662                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17663                }
17664                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17665                final ArrayList<String> pkgList = new ArrayList<String>(1);
17666                pkgList.add(deletedPackage.applicationInfo.packageName);
17667                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17668            }
17669
17670            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17671                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17672            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17673
17674            try {
17675                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17676                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17677                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17678                        installReason);
17679
17680                // Update the in-memory copy of the previous code paths.
17681                PackageSetting ps = mSettings.mPackages.get(pkgName);
17682                if (!killApp) {
17683                    if (ps.oldCodePaths == null) {
17684                        ps.oldCodePaths = new ArraySet<>();
17685                    }
17686                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17687                    if (deletedPackage.splitCodePaths != null) {
17688                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17689                    }
17690                } else {
17691                    ps.oldCodePaths = null;
17692                }
17693                if (ps.childPackageNames != null) {
17694                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17695                        final String childPkgName = ps.childPackageNames.get(i);
17696                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17697                        childPs.oldCodePaths = ps.oldCodePaths;
17698                    }
17699                }
17700                // set instant app status, but, only if it's explicitly specified
17701                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17702                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17703                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17704                prepareAppDataAfterInstallLIF(newPackage);
17705                addedPkg = true;
17706                mDexManager.notifyPackageUpdated(newPackage.packageName,
17707                        newPackage.baseCodePath, newPackage.splitCodePaths);
17708            } catch (PackageManagerException e) {
17709                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17710            }
17711        }
17712
17713        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17714            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17715
17716            // Revert all internal state mutations and added folders for the failed install
17717            if (addedPkg) {
17718                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17719                        res.removedInfo, true, null);
17720            }
17721
17722            // Restore the old package
17723            if (deletedPkg) {
17724                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17725                File restoreFile = new File(deletedPackage.codePath);
17726                // Parse old package
17727                boolean oldExternal = isExternal(deletedPackage);
17728                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17729                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17730                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17731                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17732                try {
17733                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17734                            null);
17735                } catch (PackageManagerException e) {
17736                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17737                            + e.getMessage());
17738                    return;
17739                }
17740
17741                synchronized (mPackages) {
17742                    // Ensure the installer package name up to date
17743                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17744
17745                    // Update permissions for restored package
17746                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17747
17748                    mSettings.writeLPr();
17749                }
17750
17751                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17752            }
17753        } else {
17754            synchronized (mPackages) {
17755                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17756                if (ps != null) {
17757                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17758                    if (res.removedInfo.removedChildPackages != null) {
17759                        final int childCount = res.removedInfo.removedChildPackages.size();
17760                        // Iterate in reverse as we may modify the collection
17761                        for (int i = childCount - 1; i >= 0; i--) {
17762                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17763                            if (res.addedChildPackages.containsKey(childPackageName)) {
17764                                res.removedInfo.removedChildPackages.removeAt(i);
17765                            } else {
17766                                PackageRemovedInfo childInfo = res.removedInfo
17767                                        .removedChildPackages.valueAt(i);
17768                                childInfo.removedForAllUsers = mPackages.get(
17769                                        childInfo.removedPackage) == null;
17770                            }
17771                        }
17772                    }
17773                }
17774            }
17775        }
17776    }
17777
17778    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17779            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17780            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17781            int installReason) {
17782        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17783                + ", old=" + deletedPackage);
17784
17785        final boolean disabledSystem;
17786
17787        // Remove existing system package
17788        removePackageLI(deletedPackage, true);
17789
17790        synchronized (mPackages) {
17791            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17792        }
17793        if (!disabledSystem) {
17794            // We didn't need to disable the .apk as a current system package,
17795            // which means we are replacing another update that is already
17796            // installed.  We need to make sure to delete the older one's .apk.
17797            res.removedInfo.args = createInstallArgsForExisting(0,
17798                    deletedPackage.applicationInfo.getCodePath(),
17799                    deletedPackage.applicationInfo.getResourcePath(),
17800                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17801        } else {
17802            res.removedInfo.args = null;
17803        }
17804
17805        // Successfully disabled the old package. Now proceed with re-installation
17806        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17807                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17808        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17809
17810        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17811        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17812                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17813
17814        PackageParser.Package newPackage = null;
17815        try {
17816            // Add the package to the internal data structures
17817            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17818
17819            // Set the update and install times
17820            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17821            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17822                    System.currentTimeMillis());
17823
17824            // Update the package dynamic state if succeeded
17825            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17826                // Now that the install succeeded make sure we remove data
17827                // directories for any child package the update removed.
17828                final int deletedChildCount = (deletedPackage.childPackages != null)
17829                        ? deletedPackage.childPackages.size() : 0;
17830                final int newChildCount = (newPackage.childPackages != null)
17831                        ? newPackage.childPackages.size() : 0;
17832                for (int i = 0; i < deletedChildCount; i++) {
17833                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17834                    boolean childPackageDeleted = true;
17835                    for (int j = 0; j < newChildCount; j++) {
17836                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17837                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17838                            childPackageDeleted = false;
17839                            break;
17840                        }
17841                    }
17842                    if (childPackageDeleted) {
17843                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17844                                deletedChildPkg.packageName);
17845                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17846                            PackageRemovedInfo removedChildRes = res.removedInfo
17847                                    .removedChildPackages.get(deletedChildPkg.packageName);
17848                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17849                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17850                        }
17851                    }
17852                }
17853
17854                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17855                        installReason);
17856                prepareAppDataAfterInstallLIF(newPackage);
17857
17858                mDexManager.notifyPackageUpdated(newPackage.packageName,
17859                            newPackage.baseCodePath, newPackage.splitCodePaths);
17860            }
17861        } catch (PackageManagerException e) {
17862            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17863            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17864        }
17865
17866        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17867            // Re installation failed. Restore old information
17868            // Remove new pkg information
17869            if (newPackage != null) {
17870                removeInstalledPackageLI(newPackage, true);
17871            }
17872            // Add back the old system package
17873            try {
17874                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17875            } catch (PackageManagerException e) {
17876                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17877            }
17878
17879            synchronized (mPackages) {
17880                if (disabledSystem) {
17881                    enableSystemPackageLPw(deletedPackage);
17882                }
17883
17884                // Ensure the installer package name up to date
17885                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17886
17887                // Update permissions for restored package
17888                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17889
17890                mSettings.writeLPr();
17891            }
17892
17893            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17894                    + " after failed upgrade");
17895        }
17896    }
17897
17898    /**
17899     * Checks whether the parent or any of the child packages have a change shared
17900     * user. For a package to be a valid update the shred users of the parent and
17901     * the children should match. We may later support changing child shared users.
17902     * @param oldPkg The updated package.
17903     * @param newPkg The update package.
17904     * @return The shared user that change between the versions.
17905     */
17906    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17907            PackageParser.Package newPkg) {
17908        // Check parent shared user
17909        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17910            return newPkg.packageName;
17911        }
17912        // Check child shared users
17913        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17914        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17915        for (int i = 0; i < newChildCount; i++) {
17916            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17917            // If this child was present, did it have the same shared user?
17918            for (int j = 0; j < oldChildCount; j++) {
17919                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17920                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17921                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17922                    return newChildPkg.packageName;
17923                }
17924            }
17925        }
17926        return null;
17927    }
17928
17929    private void removeNativeBinariesLI(PackageSetting ps) {
17930        // Remove the lib path for the parent package
17931        if (ps != null) {
17932            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17933            // Remove the lib path for the child packages
17934            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17935            for (int i = 0; i < childCount; i++) {
17936                PackageSetting childPs = null;
17937                synchronized (mPackages) {
17938                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17939                }
17940                if (childPs != null) {
17941                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17942                            .legacyNativeLibraryPathString);
17943                }
17944            }
17945        }
17946    }
17947
17948    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17949        // Enable the parent package
17950        mSettings.enableSystemPackageLPw(pkg.packageName);
17951        // Enable the child packages
17952        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17953        for (int i = 0; i < childCount; i++) {
17954            PackageParser.Package childPkg = pkg.childPackages.get(i);
17955            mSettings.enableSystemPackageLPw(childPkg.packageName);
17956        }
17957    }
17958
17959    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17960            PackageParser.Package newPkg) {
17961        // Disable the parent package (parent always replaced)
17962        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17963        // Disable the child packages
17964        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17965        for (int i = 0; i < childCount; i++) {
17966            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17967            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17968            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17969        }
17970        return disabled;
17971    }
17972
17973    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17974            String installerPackageName) {
17975        // Enable the parent package
17976        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17977        // Enable the child packages
17978        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17979        for (int i = 0; i < childCount; i++) {
17980            PackageParser.Package childPkg = pkg.childPackages.get(i);
17981            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17982        }
17983    }
17984
17985    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17986        // Collect all used permissions in the UID
17987        ArraySet<String> usedPermissions = new ArraySet<>();
17988        final int packageCount = su.packages.size();
17989        for (int i = 0; i < packageCount; i++) {
17990            PackageSetting ps = su.packages.valueAt(i);
17991            if (ps.pkg == null) {
17992                continue;
17993            }
17994            final int requestedPermCount = ps.pkg.requestedPermissions.size();
17995            for (int j = 0; j < requestedPermCount; j++) {
17996                String permission = ps.pkg.requestedPermissions.get(j);
17997                BasePermission bp = mSettings.mPermissions.get(permission);
17998                if (bp != null) {
17999                    usedPermissions.add(permission);
18000                }
18001            }
18002        }
18003
18004        PermissionsState permissionsState = su.getPermissionsState();
18005        // Prune install permissions
18006        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
18007        final int installPermCount = installPermStates.size();
18008        for (int i = installPermCount - 1; i >= 0;  i--) {
18009            PermissionState permissionState = installPermStates.get(i);
18010            if (!usedPermissions.contains(permissionState.getName())) {
18011                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18012                if (bp != null) {
18013                    permissionsState.revokeInstallPermission(bp);
18014                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
18015                            PackageManager.MASK_PERMISSION_FLAGS, 0);
18016                }
18017            }
18018        }
18019
18020        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
18021
18022        // Prune runtime permissions
18023        for (int userId : allUserIds) {
18024            List<PermissionState> runtimePermStates = permissionsState
18025                    .getRuntimePermissionStates(userId);
18026            final int runtimePermCount = runtimePermStates.size();
18027            for (int i = runtimePermCount - 1; i >= 0; i--) {
18028                PermissionState permissionState = runtimePermStates.get(i);
18029                if (!usedPermissions.contains(permissionState.getName())) {
18030                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
18031                    if (bp != null) {
18032                        permissionsState.revokeRuntimePermission(bp, userId);
18033                        permissionsState.updatePermissionFlags(bp, userId,
18034                                PackageManager.MASK_PERMISSION_FLAGS, 0);
18035                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
18036                                runtimePermissionChangedUserIds, userId);
18037                    }
18038                }
18039            }
18040        }
18041
18042        return runtimePermissionChangedUserIds;
18043    }
18044
18045    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
18046            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
18047        // Update the parent package setting
18048        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
18049                res, user, installReason);
18050        // Update the child packages setting
18051        final int childCount = (newPackage.childPackages != null)
18052                ? newPackage.childPackages.size() : 0;
18053        for (int i = 0; i < childCount; i++) {
18054            PackageParser.Package childPackage = newPackage.childPackages.get(i);
18055            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
18056            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
18057                    childRes.origUsers, childRes, user, installReason);
18058        }
18059    }
18060
18061    private void updateSettingsInternalLI(PackageParser.Package newPackage,
18062            String installerPackageName, int[] allUsers, int[] installedForUsers,
18063            PackageInstalledInfo res, UserHandle user, int installReason) {
18064        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
18065
18066        String pkgName = newPackage.packageName;
18067        synchronized (mPackages) {
18068            //write settings. the installStatus will be incomplete at this stage.
18069            //note that the new package setting would have already been
18070            //added to mPackages. It hasn't been persisted yet.
18071            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
18072            // TODO: Remove this write? It's also written at the end of this method
18073            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18074            mSettings.writeLPr();
18075            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18076        }
18077
18078        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
18079        synchronized (mPackages) {
18080            updatePermissionsLPw(newPackage.packageName, newPackage,
18081                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
18082                            ? UPDATE_PERMISSIONS_ALL : 0));
18083            // For system-bundled packages, we assume that installing an upgraded version
18084            // of the package implies that the user actually wants to run that new code,
18085            // so we enable the package.
18086            PackageSetting ps = mSettings.mPackages.get(pkgName);
18087            final int userId = user.getIdentifier();
18088            if (ps != null) {
18089                if (isSystemApp(newPackage)) {
18090                    if (DEBUG_INSTALL) {
18091                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
18092                    }
18093                    // Enable system package for requested users
18094                    if (res.origUsers != null) {
18095                        for (int origUserId : res.origUsers) {
18096                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
18097                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
18098                                        origUserId, installerPackageName);
18099                            }
18100                        }
18101                    }
18102                    // Also convey the prior install/uninstall state
18103                    if (allUsers != null && installedForUsers != null) {
18104                        for (int currentUserId : allUsers) {
18105                            final boolean installed = ArrayUtils.contains(
18106                                    installedForUsers, currentUserId);
18107                            if (DEBUG_INSTALL) {
18108                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
18109                            }
18110                            ps.setInstalled(installed, currentUserId);
18111                        }
18112                        // these install state changes will be persisted in the
18113                        // upcoming call to mSettings.writeLPr().
18114                    }
18115                }
18116                // It's implied that when a user requests installation, they want the app to be
18117                // installed and enabled.
18118                if (userId != UserHandle.USER_ALL) {
18119                    ps.setInstalled(true, userId);
18120                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
18121                }
18122
18123                // When replacing an existing package, preserve the original install reason for all
18124                // users that had the package installed before.
18125                final Set<Integer> previousUserIds = new ArraySet<>();
18126                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
18127                    final int installReasonCount = res.removedInfo.installReasons.size();
18128                    for (int i = 0; i < installReasonCount; i++) {
18129                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
18130                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
18131                        ps.setInstallReason(previousInstallReason, previousUserId);
18132                        previousUserIds.add(previousUserId);
18133                    }
18134                }
18135
18136                // Set install reason for users that are having the package newly installed.
18137                if (userId == UserHandle.USER_ALL) {
18138                    for (int currentUserId : sUserManager.getUserIds()) {
18139                        if (!previousUserIds.contains(currentUserId)) {
18140                            ps.setInstallReason(installReason, currentUserId);
18141                        }
18142                    }
18143                } else if (!previousUserIds.contains(userId)) {
18144                    ps.setInstallReason(installReason, userId);
18145                }
18146                mSettings.writeKernelMappingLPr(ps);
18147            }
18148            res.name = pkgName;
18149            res.uid = newPackage.applicationInfo.uid;
18150            res.pkg = newPackage;
18151            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
18152            mSettings.setInstallerPackageName(pkgName, installerPackageName);
18153            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18154            //to update install status
18155            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
18156            mSettings.writeLPr();
18157            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18158        }
18159
18160        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18161    }
18162
18163    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
18164        try {
18165            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
18166            installPackageLI(args, res);
18167        } finally {
18168            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18169        }
18170    }
18171
18172    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
18173        final int installFlags = args.installFlags;
18174        final String installerPackageName = args.installerPackageName;
18175        final String volumeUuid = args.volumeUuid;
18176        final File tmpPackageFile = new File(args.getCodePath());
18177        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
18178        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
18179                || (args.volumeUuid != null));
18180        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
18181        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
18182        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
18183        boolean replace = false;
18184        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
18185        if (args.move != null) {
18186            // moving a complete application; perform an initial scan on the new install location
18187            scanFlags |= SCAN_INITIAL;
18188        }
18189        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
18190            scanFlags |= SCAN_DONT_KILL_APP;
18191        }
18192        if (instantApp) {
18193            scanFlags |= SCAN_AS_INSTANT_APP;
18194        }
18195        if (fullApp) {
18196            scanFlags |= SCAN_AS_FULL_APP;
18197        }
18198
18199        // Result object to be returned
18200        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18201
18202        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
18203
18204        // Sanity check
18205        if (instantApp && (forwardLocked || onExternal)) {
18206            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
18207                    + " external=" + onExternal);
18208            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
18209            return;
18210        }
18211
18212        // Retrieve PackageSettings and parse package
18213        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
18214                | PackageParser.PARSE_ENFORCE_CODE
18215                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
18216                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
18217                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
18218                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
18219        PackageParser pp = new PackageParser();
18220        pp.setSeparateProcesses(mSeparateProcesses);
18221        pp.setDisplayMetrics(mMetrics);
18222        pp.setCallback(mPackageParserCallback);
18223
18224        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
18225        final PackageParser.Package pkg;
18226        try {
18227            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
18228        } catch (PackageParserException e) {
18229            res.setError("Failed parse during installPackageLI", e);
18230            return;
18231        } finally {
18232            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18233        }
18234
18235        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
18236        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
18237            Slog.w(TAG, "Instant app package " + pkg.packageName + " does not target O");
18238            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18239                    "Instant app package must target O");
18240            return;
18241        }
18242        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
18243            Slog.w(TAG, "Instant app package " + pkg.packageName
18244                    + " does not target targetSandboxVersion 2");
18245            res.setError(INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18246                    "Instant app package must use targetSanboxVersion 2");
18247            return;
18248        }
18249
18250        if (pkg.applicationInfo.isStaticSharedLibrary()) {
18251            // Static shared libraries have synthetic package names
18252            renameStaticSharedLibraryPackage(pkg);
18253
18254            // No static shared libs on external storage
18255            if (onExternal) {
18256                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
18257                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18258                        "Packages declaring static-shared libs cannot be updated");
18259                return;
18260            }
18261        }
18262
18263        // If we are installing a clustered package add results for the children
18264        if (pkg.childPackages != null) {
18265            synchronized (mPackages) {
18266                final int childCount = pkg.childPackages.size();
18267                for (int i = 0; i < childCount; i++) {
18268                    PackageParser.Package childPkg = pkg.childPackages.get(i);
18269                    PackageInstalledInfo childRes = new PackageInstalledInfo();
18270                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
18271                    childRes.pkg = childPkg;
18272                    childRes.name = childPkg.packageName;
18273                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18274                    if (childPs != null) {
18275                        childRes.origUsers = childPs.queryInstalledUsers(
18276                                sUserManager.getUserIds(), true);
18277                    }
18278                    if ((mPackages.containsKey(childPkg.packageName))) {
18279                        childRes.removedInfo = new PackageRemovedInfo(this);
18280                        childRes.removedInfo.removedPackage = childPkg.packageName;
18281                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
18282                    }
18283                    if (res.addedChildPackages == null) {
18284                        res.addedChildPackages = new ArrayMap<>();
18285                    }
18286                    res.addedChildPackages.put(childPkg.packageName, childRes);
18287                }
18288            }
18289        }
18290
18291        // If package doesn't declare API override, mark that we have an install
18292        // time CPU ABI override.
18293        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
18294            pkg.cpuAbiOverride = args.abiOverride;
18295        }
18296
18297        String pkgName = res.name = pkg.packageName;
18298        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
18299            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
18300                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
18301                return;
18302            }
18303        }
18304
18305        try {
18306            // either use what we've been given or parse directly from the APK
18307            if (args.certificates != null) {
18308                try {
18309                    PackageParser.populateCertificates(pkg, args.certificates);
18310                } catch (PackageParserException e) {
18311                    // there was something wrong with the certificates we were given;
18312                    // try to pull them from the APK
18313                    PackageParser.collectCertificates(pkg, parseFlags);
18314                }
18315            } else {
18316                PackageParser.collectCertificates(pkg, parseFlags);
18317            }
18318        } catch (PackageParserException e) {
18319            res.setError("Failed collect during installPackageLI", e);
18320            return;
18321        }
18322
18323        // Get rid of all references to package scan path via parser.
18324        pp = null;
18325        String oldCodePath = null;
18326        boolean systemApp = false;
18327        synchronized (mPackages) {
18328            // Check if installing already existing package
18329            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
18330                String oldName = mSettings.getRenamedPackageLPr(pkgName);
18331                if (pkg.mOriginalPackages != null
18332                        && pkg.mOriginalPackages.contains(oldName)
18333                        && mPackages.containsKey(oldName)) {
18334                    // This package is derived from an original package,
18335                    // and this device has been updating from that original
18336                    // name.  We must continue using the original name, so
18337                    // rename the new package here.
18338                    pkg.setPackageName(oldName);
18339                    pkgName = pkg.packageName;
18340                    replace = true;
18341                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18342                            + oldName + " pkgName=" + pkgName);
18343                } else if (mPackages.containsKey(pkgName)) {
18344                    // This package, under its official name, already exists
18345                    // on the device; we should replace it.
18346                    replace = true;
18347                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18348                }
18349
18350                // Child packages are installed through the parent package
18351                if (pkg.parentPackage != null) {
18352                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18353                            "Package " + pkg.packageName + " is child of package "
18354                                    + pkg.parentPackage.parentPackage + ". Child packages "
18355                                    + "can be updated only through the parent package.");
18356                    return;
18357                }
18358
18359                if (replace) {
18360                    // Prevent apps opting out from runtime permissions
18361                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18362                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18363                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18364                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18365                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18366                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18367                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18368                                        + " doesn't support runtime permissions but the old"
18369                                        + " target SDK " + oldTargetSdk + " does.");
18370                        return;
18371                    }
18372                    // Prevent apps from downgrading their targetSandbox.
18373                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18374                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18375                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18376                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18377                                "Package " + pkg.packageName + " new target sandbox "
18378                                + newTargetSandbox + " is incompatible with the previous value of"
18379                                + oldTargetSandbox + ".");
18380                        return;
18381                    }
18382
18383                    // Prevent installing of child packages
18384                    if (oldPackage.parentPackage != null) {
18385                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18386                                "Package " + pkg.packageName + " is child of package "
18387                                        + oldPackage.parentPackage + ". Child packages "
18388                                        + "can be updated only through the parent package.");
18389                        return;
18390                    }
18391                }
18392            }
18393
18394            PackageSetting ps = mSettings.mPackages.get(pkgName);
18395            if (ps != null) {
18396                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18397
18398                // Static shared libs have same package with different versions where
18399                // we internally use a synthetic package name to allow multiple versions
18400                // of the same package, therefore we need to compare signatures against
18401                // the package setting for the latest library version.
18402                PackageSetting signatureCheckPs = ps;
18403                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18404                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18405                    if (libraryEntry != null) {
18406                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18407                    }
18408                }
18409
18410                // Quick sanity check that we're signed correctly if updating;
18411                // we'll check this again later when scanning, but we want to
18412                // bail early here before tripping over redefined permissions.
18413                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18414                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18415                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18416                                + pkg.packageName + " upgrade keys do not match the "
18417                                + "previously installed version");
18418                        return;
18419                    }
18420                } else {
18421                    try {
18422                        verifySignaturesLP(signatureCheckPs, pkg);
18423                    } catch (PackageManagerException e) {
18424                        res.setError(e.error, e.getMessage());
18425                        return;
18426                    }
18427                }
18428
18429                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18430                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18431                    systemApp = (ps.pkg.applicationInfo.flags &
18432                            ApplicationInfo.FLAG_SYSTEM) != 0;
18433                }
18434                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18435            }
18436
18437            int N = pkg.permissions.size();
18438            for (int i = N-1; i >= 0; i--) {
18439                PackageParser.Permission perm = pkg.permissions.get(i);
18440                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18441
18442                // Don't allow anyone but the system to define ephemeral permissions.
18443                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
18444                        && !systemApp) {
18445                    Slog.w(TAG, "Non-System package " + pkg.packageName
18446                            + " attempting to delcare ephemeral permission "
18447                            + perm.info.name + "; Removing ephemeral.");
18448                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
18449                }
18450                // Check whether the newly-scanned package wants to define an already-defined perm
18451                if (bp != null) {
18452                    // If the defining package is signed with our cert, it's okay.  This
18453                    // also includes the "updating the same package" case, of course.
18454                    // "updating same package" could also involve key-rotation.
18455                    final boolean sigsOk;
18456                    if (bp.sourcePackage.equals(pkg.packageName)
18457                            && (bp.packageSetting instanceof PackageSetting)
18458                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18459                                    scanFlags))) {
18460                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18461                    } else {
18462                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18463                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18464                    }
18465                    if (!sigsOk) {
18466                        // If the owning package is the system itself, we log but allow
18467                        // install to proceed; we fail the install on all other permission
18468                        // redefinitions.
18469                        if (!bp.sourcePackage.equals("android")) {
18470                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18471                                    + pkg.packageName + " attempting to redeclare permission "
18472                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18473                            res.origPermission = perm.info.name;
18474                            res.origPackage = bp.sourcePackage;
18475                            return;
18476                        } else {
18477                            Slog.w(TAG, "Package " + pkg.packageName
18478                                    + " attempting to redeclare system permission "
18479                                    + perm.info.name + "; ignoring new declaration");
18480                            pkg.permissions.remove(i);
18481                        }
18482                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18483                        // Prevent apps to change protection level to dangerous from any other
18484                        // type as this would allow a privilege escalation where an app adds a
18485                        // normal/signature permission in other app's group and later redefines
18486                        // it as dangerous leading to the group auto-grant.
18487                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18488                                == PermissionInfo.PROTECTION_DANGEROUS) {
18489                            if (bp != null && !bp.isRuntime()) {
18490                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18491                                        + "non-runtime permission " + perm.info.name
18492                                        + " to runtime; keeping old protection level");
18493                                perm.info.protectionLevel = bp.protectionLevel;
18494                            }
18495                        }
18496                    }
18497                }
18498            }
18499        }
18500
18501        if (systemApp) {
18502            if (onExternal) {
18503                // Abort update; system app can't be replaced with app on sdcard
18504                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18505                        "Cannot install updates to system apps on sdcard");
18506                return;
18507            } else if (instantApp) {
18508                // Abort update; system app can't be replaced with an instant app
18509                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18510                        "Cannot update a system app with an instant app");
18511                return;
18512            }
18513        }
18514
18515        if (args.move != null) {
18516            // We did an in-place move, so dex is ready to roll
18517            scanFlags |= SCAN_NO_DEX;
18518            scanFlags |= SCAN_MOVE;
18519
18520            synchronized (mPackages) {
18521                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18522                if (ps == null) {
18523                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18524                            "Missing settings for moved package " + pkgName);
18525                }
18526
18527                // We moved the entire application as-is, so bring over the
18528                // previously derived ABI information.
18529                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18530                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18531            }
18532
18533        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18534            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18535            scanFlags |= SCAN_NO_DEX;
18536
18537            try {
18538                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18539                    args.abiOverride : pkg.cpuAbiOverride);
18540                final boolean extractNativeLibs = !pkg.isLibrary();
18541                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18542                        extractNativeLibs, mAppLib32InstallDir);
18543            } catch (PackageManagerException pme) {
18544                Slog.e(TAG, "Error deriving application ABI", pme);
18545                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18546                return;
18547            }
18548
18549            // Shared libraries for the package need to be updated.
18550            synchronized (mPackages) {
18551                try {
18552                    updateSharedLibrariesLPr(pkg, null);
18553                } catch (PackageManagerException e) {
18554                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18555                }
18556            }
18557
18558            // dexopt can take some time to complete, so, for instant apps, we skip this
18559            // step during installation. Instead, we'll take extra time the first time the
18560            // instant app starts. It's preferred to do it this way to provide continuous
18561            // progress to the user instead of mysteriously blocking somewhere in the
18562            // middle of running an instant app. The default behaviour can be overridden
18563            // via gservices.
18564            if (!instantApp || Global.getInt(
18565                        mContext.getContentResolver(), Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0) {
18566                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18567                // Do not run PackageDexOptimizer through the local performDexOpt
18568                // method because `pkg` may not be in `mPackages` yet.
18569                //
18570                // Also, don't fail application installs if the dexopt step fails.
18571                DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
18572                        REASON_INSTALL,
18573                        DexoptOptions.DEXOPT_BOOT_COMPLETE);
18574                mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18575                        null /* instructionSets */,
18576                        getOrCreateCompilerPackageStats(pkg),
18577                        mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
18578                        dexoptOptions);
18579                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18580            }
18581
18582            // Notify BackgroundDexOptService that the package has been changed.
18583            // If this is an update of a package which used to fail to compile,
18584            // BDOS will remove it from its blacklist.
18585            // TODO: Layering violation
18586            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18587        }
18588
18589        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18590            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18591            return;
18592        }
18593
18594        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18595
18596        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18597                "installPackageLI")) {
18598            if (replace) {
18599                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18600                    // Static libs have a synthetic package name containing the version
18601                    // and cannot be updated as an update would get a new package name,
18602                    // unless this is the exact same version code which is useful for
18603                    // development.
18604                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18605                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18606                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18607                                + "static-shared libs cannot be updated");
18608                        return;
18609                    }
18610                }
18611                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18612                        installerPackageName, res, args.installReason);
18613            } else {
18614                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18615                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18616            }
18617        }
18618
18619        synchronized (mPackages) {
18620            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18621            if (ps != null) {
18622                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18623                ps.setUpdateAvailable(false /*updateAvailable*/);
18624            }
18625
18626            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18627            for (int i = 0; i < childCount; i++) {
18628                PackageParser.Package childPkg = pkg.childPackages.get(i);
18629                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18630                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18631                if (childPs != null) {
18632                    childRes.newUsers = childPs.queryInstalledUsers(
18633                            sUserManager.getUserIds(), true);
18634                }
18635            }
18636
18637            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18638                updateSequenceNumberLP(ps, res.newUsers);
18639                updateInstantAppInstallerLocked(pkgName);
18640            }
18641        }
18642    }
18643
18644    private void startIntentFilterVerifications(int userId, boolean replacing,
18645            PackageParser.Package pkg) {
18646        if (mIntentFilterVerifierComponent == null) {
18647            Slog.w(TAG, "No IntentFilter verification will not be done as "
18648                    + "there is no IntentFilterVerifier available!");
18649            return;
18650        }
18651
18652        final int verifierUid = getPackageUid(
18653                mIntentFilterVerifierComponent.getPackageName(),
18654                MATCH_DEBUG_TRIAGED_MISSING,
18655                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18656
18657        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18658        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18659        mHandler.sendMessage(msg);
18660
18661        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18662        for (int i = 0; i < childCount; i++) {
18663            PackageParser.Package childPkg = pkg.childPackages.get(i);
18664            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18665            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18666            mHandler.sendMessage(msg);
18667        }
18668    }
18669
18670    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18671            PackageParser.Package pkg) {
18672        int size = pkg.activities.size();
18673        if (size == 0) {
18674            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18675                    "No activity, so no need to verify any IntentFilter!");
18676            return;
18677        }
18678
18679        final boolean hasDomainURLs = hasDomainURLs(pkg);
18680        if (!hasDomainURLs) {
18681            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18682                    "No domain URLs, so no need to verify any IntentFilter!");
18683            return;
18684        }
18685
18686        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18687                + " if any IntentFilter from the " + size
18688                + " Activities needs verification ...");
18689
18690        int count = 0;
18691        final String packageName = pkg.packageName;
18692
18693        synchronized (mPackages) {
18694            // If this is a new install and we see that we've already run verification for this
18695            // package, we have nothing to do: it means the state was restored from backup.
18696            if (!replacing) {
18697                IntentFilterVerificationInfo ivi =
18698                        mSettings.getIntentFilterVerificationLPr(packageName);
18699                if (ivi != null) {
18700                    if (DEBUG_DOMAIN_VERIFICATION) {
18701                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18702                                + ivi.getStatusString());
18703                    }
18704                    return;
18705                }
18706            }
18707
18708            // If any filters need to be verified, then all need to be.
18709            boolean needToVerify = false;
18710            for (PackageParser.Activity a : pkg.activities) {
18711                for (ActivityIntentInfo filter : a.intents) {
18712                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18713                        if (DEBUG_DOMAIN_VERIFICATION) {
18714                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18715                        }
18716                        needToVerify = true;
18717                        break;
18718                    }
18719                }
18720            }
18721
18722            if (needToVerify) {
18723                final int verificationId = mIntentFilterVerificationToken++;
18724                for (PackageParser.Activity a : pkg.activities) {
18725                    for (ActivityIntentInfo filter : a.intents) {
18726                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18727                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18728                                    "Verification needed for IntentFilter:" + filter.toString());
18729                            mIntentFilterVerifier.addOneIntentFilterVerification(
18730                                    verifierUid, userId, verificationId, filter, packageName);
18731                            count++;
18732                        }
18733                    }
18734                }
18735            }
18736        }
18737
18738        if (count > 0) {
18739            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18740                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18741                    +  " for userId:" + userId);
18742            mIntentFilterVerifier.startVerifications(userId);
18743        } else {
18744            if (DEBUG_DOMAIN_VERIFICATION) {
18745                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18746            }
18747        }
18748    }
18749
18750    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18751        final ComponentName cn  = filter.activity.getComponentName();
18752        final String packageName = cn.getPackageName();
18753
18754        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18755                packageName);
18756        if (ivi == null) {
18757            return true;
18758        }
18759        int status = ivi.getStatus();
18760        switch (status) {
18761            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18762            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18763                return true;
18764
18765            default:
18766                // Nothing to do
18767                return false;
18768        }
18769    }
18770
18771    private static boolean isMultiArch(ApplicationInfo info) {
18772        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18773    }
18774
18775    private static boolean isExternal(PackageParser.Package pkg) {
18776        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18777    }
18778
18779    private static boolean isExternal(PackageSetting ps) {
18780        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18781    }
18782
18783    private static boolean isSystemApp(PackageParser.Package pkg) {
18784        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18785    }
18786
18787    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18788        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18789    }
18790
18791    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18792        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18793    }
18794
18795    private static boolean isSystemApp(PackageSetting ps) {
18796        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18797    }
18798
18799    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18800        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18801    }
18802
18803    private int packageFlagsToInstallFlags(PackageSetting ps) {
18804        int installFlags = 0;
18805        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18806            // This existing package was an external ASEC install when we have
18807            // the external flag without a UUID
18808            installFlags |= PackageManager.INSTALL_EXTERNAL;
18809        }
18810        if (ps.isForwardLocked()) {
18811            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18812        }
18813        return installFlags;
18814    }
18815
18816    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18817        if (isExternal(pkg)) {
18818            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18819                return StorageManager.UUID_PRIMARY_PHYSICAL;
18820            } else {
18821                return pkg.volumeUuid;
18822            }
18823        } else {
18824            return StorageManager.UUID_PRIVATE_INTERNAL;
18825        }
18826    }
18827
18828    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18829        if (isExternal(pkg)) {
18830            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18831                return mSettings.getExternalVersion();
18832            } else {
18833                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18834            }
18835        } else {
18836            return mSettings.getInternalVersion();
18837        }
18838    }
18839
18840    private void deleteTempPackageFiles() {
18841        final FilenameFilter filter = new FilenameFilter() {
18842            public boolean accept(File dir, String name) {
18843                return name.startsWith("vmdl") && name.endsWith(".tmp");
18844            }
18845        };
18846        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18847            file.delete();
18848        }
18849    }
18850
18851    @Override
18852    public void deletePackageAsUser(String packageName, int versionCode,
18853            IPackageDeleteObserver observer, int userId, int flags) {
18854        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18855                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18856    }
18857
18858    @Override
18859    public void deletePackageVersioned(VersionedPackage versionedPackage,
18860            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18861        final int callingUid = Binder.getCallingUid();
18862        mContext.enforceCallingOrSelfPermission(
18863                android.Manifest.permission.DELETE_PACKAGES, null);
18864        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18865        Preconditions.checkNotNull(versionedPackage);
18866        Preconditions.checkNotNull(observer);
18867        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18868                PackageManager.VERSION_CODE_HIGHEST,
18869                Integer.MAX_VALUE, "versionCode must be >= -1");
18870
18871        final String packageName = versionedPackage.getPackageName();
18872        final int versionCode = versionedPackage.getVersionCode();
18873        final String internalPackageName;
18874        synchronized (mPackages) {
18875            // Normalize package name to handle renamed packages and static libs
18876            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18877                    versionedPackage.getVersionCode());
18878        }
18879
18880        final int uid = Binder.getCallingUid();
18881        if (!isOrphaned(internalPackageName)
18882                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18883            try {
18884                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18885                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18886                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18887                observer.onUserActionRequired(intent);
18888            } catch (RemoteException re) {
18889            }
18890            return;
18891        }
18892        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18893        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18894        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18895            mContext.enforceCallingOrSelfPermission(
18896                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18897                    "deletePackage for user " + userId);
18898        }
18899
18900        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18901            try {
18902                observer.onPackageDeleted(packageName,
18903                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18904            } catch (RemoteException re) {
18905            }
18906            return;
18907        }
18908
18909        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18910            try {
18911                observer.onPackageDeleted(packageName,
18912                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18913            } catch (RemoteException re) {
18914            }
18915            return;
18916        }
18917
18918        if (DEBUG_REMOVE) {
18919            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18920                    + " deleteAllUsers: " + deleteAllUsers + " version="
18921                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18922                    ? "VERSION_CODE_HIGHEST" : versionCode));
18923        }
18924        // Queue up an async operation since the package deletion may take a little while.
18925        mHandler.post(new Runnable() {
18926            public void run() {
18927                mHandler.removeCallbacks(this);
18928                int returnCode;
18929                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18930                boolean doDeletePackage = true;
18931                if (ps != null) {
18932                    final boolean targetIsInstantApp =
18933                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18934                    doDeletePackage = !targetIsInstantApp
18935                            || canViewInstantApps;
18936                }
18937                if (doDeletePackage) {
18938                    if (!deleteAllUsers) {
18939                        returnCode = deletePackageX(internalPackageName, versionCode,
18940                                userId, deleteFlags);
18941                    } else {
18942                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
18943                                internalPackageName, users);
18944                        // If nobody is blocking uninstall, proceed with delete for all users
18945                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18946                            returnCode = deletePackageX(internalPackageName, versionCode,
18947                                    userId, deleteFlags);
18948                        } else {
18949                            // Otherwise uninstall individually for users with blockUninstalls=false
18950                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18951                            for (int userId : users) {
18952                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18953                                    returnCode = deletePackageX(internalPackageName, versionCode,
18954                                            userId, userFlags);
18955                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18956                                        Slog.w(TAG, "Package delete failed for user " + userId
18957                                                + ", returnCode " + returnCode);
18958                                    }
18959                                }
18960                            }
18961                            // The app has only been marked uninstalled for certain users.
18962                            // We still need to report that delete was blocked
18963                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18964                        }
18965                    }
18966                } else {
18967                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18968                }
18969                try {
18970                    observer.onPackageDeleted(packageName, returnCode, null);
18971                } catch (RemoteException e) {
18972                    Log.i(TAG, "Observer no longer exists.");
18973                } //end catch
18974            } //end run
18975        });
18976    }
18977
18978    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18979        if (pkg.staticSharedLibName != null) {
18980            return pkg.manifestPackageName;
18981        }
18982        return pkg.packageName;
18983    }
18984
18985    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18986        // Handle renamed packages
18987        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18988        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18989
18990        // Is this a static library?
18991        SparseArray<SharedLibraryEntry> versionedLib =
18992                mStaticLibsByDeclaringPackage.get(packageName);
18993        if (versionedLib == null || versionedLib.size() <= 0) {
18994            return packageName;
18995        }
18996
18997        // Figure out which lib versions the caller can see
18998        SparseIntArray versionsCallerCanSee = null;
18999        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
19000        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
19001                && callingAppId != Process.ROOT_UID) {
19002            versionsCallerCanSee = new SparseIntArray();
19003            String libName = versionedLib.valueAt(0).info.getName();
19004            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
19005            if (uidPackages != null) {
19006                for (String uidPackage : uidPackages) {
19007                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
19008                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
19009                    if (libIdx >= 0) {
19010                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
19011                        versionsCallerCanSee.append(libVersion, libVersion);
19012                    }
19013                }
19014            }
19015        }
19016
19017        // Caller can see nothing - done
19018        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
19019            return packageName;
19020        }
19021
19022        // Find the version the caller can see and the app version code
19023        SharedLibraryEntry highestVersion = null;
19024        final int versionCount = versionedLib.size();
19025        for (int i = 0; i < versionCount; i++) {
19026            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
19027            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
19028                    libEntry.info.getVersion()) < 0) {
19029                continue;
19030            }
19031            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
19032            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
19033                if (libVersionCode == versionCode) {
19034                    return libEntry.apk;
19035                }
19036            } else if (highestVersion == null) {
19037                highestVersion = libEntry;
19038            } else if (libVersionCode  > highestVersion.info
19039                    .getDeclaringPackage().getVersionCode()) {
19040                highestVersion = libEntry;
19041            }
19042        }
19043
19044        if (highestVersion != null) {
19045            return highestVersion.apk;
19046        }
19047
19048        return packageName;
19049    }
19050
19051    boolean isCallerVerifier(int callingUid) {
19052        final int callingUserId = UserHandle.getUserId(callingUid);
19053        return mRequiredVerifierPackage != null &&
19054                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
19055    }
19056
19057    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
19058        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
19059              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19060            return true;
19061        }
19062        final int callingUserId = UserHandle.getUserId(callingUid);
19063        // If the caller installed the pkgName, then allow it to silently uninstall.
19064        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
19065            return true;
19066        }
19067
19068        // Allow package verifier to silently uninstall.
19069        if (mRequiredVerifierPackage != null &&
19070                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
19071            return true;
19072        }
19073
19074        // Allow package uninstaller to silently uninstall.
19075        if (mRequiredUninstallerPackage != null &&
19076                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
19077            return true;
19078        }
19079
19080        // Allow storage manager to silently uninstall.
19081        if (mStorageManagerPackage != null &&
19082                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
19083            return true;
19084        }
19085
19086        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
19087        // uninstall for device owner provisioning.
19088        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
19089                == PERMISSION_GRANTED) {
19090            return true;
19091        }
19092
19093        return false;
19094    }
19095
19096    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
19097        int[] result = EMPTY_INT_ARRAY;
19098        for (int userId : userIds) {
19099            if (getBlockUninstallForUser(packageName, userId)) {
19100                result = ArrayUtils.appendInt(result, userId);
19101            }
19102        }
19103        return result;
19104    }
19105
19106    @Override
19107    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
19108        final int callingUid = Binder.getCallingUid();
19109        if (getInstantAppPackageName(callingUid) != null
19110                && !isCallerSameApp(packageName, callingUid)) {
19111            return false;
19112        }
19113        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
19114    }
19115
19116    private boolean isPackageDeviceAdmin(String packageName, int userId) {
19117        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
19118                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
19119        try {
19120            if (dpm != null) {
19121                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
19122                        /* callingUserOnly =*/ false);
19123                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
19124                        : deviceOwnerComponentName.getPackageName();
19125                // Does the package contains the device owner?
19126                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
19127                // this check is probably not needed, since DO should be registered as a device
19128                // admin on some user too. (Original bug for this: b/17657954)
19129                if (packageName.equals(deviceOwnerPackageName)) {
19130                    return true;
19131                }
19132                // Does it contain a device admin for any user?
19133                int[] users;
19134                if (userId == UserHandle.USER_ALL) {
19135                    users = sUserManager.getUserIds();
19136                } else {
19137                    users = new int[]{userId};
19138                }
19139                for (int i = 0; i < users.length; ++i) {
19140                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
19141                        return true;
19142                    }
19143                }
19144            }
19145        } catch (RemoteException e) {
19146        }
19147        return false;
19148    }
19149
19150    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
19151        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
19152    }
19153
19154    /**
19155     *  This method is an internal method that could be get invoked either
19156     *  to delete an installed package or to clean up a failed installation.
19157     *  After deleting an installed package, a broadcast is sent to notify any
19158     *  listeners that the package has been removed. For cleaning up a failed
19159     *  installation, the broadcast is not necessary since the package's
19160     *  installation wouldn't have sent the initial broadcast either
19161     *  The key steps in deleting a package are
19162     *  deleting the package information in internal structures like mPackages,
19163     *  deleting the packages base directories through installd
19164     *  updating mSettings to reflect current status
19165     *  persisting settings for later use
19166     *  sending a broadcast if necessary
19167     */
19168    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
19169        final PackageRemovedInfo info = new PackageRemovedInfo(this);
19170        final boolean res;
19171
19172        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
19173                ? UserHandle.USER_ALL : userId;
19174
19175        if (isPackageDeviceAdmin(packageName, removeUser)) {
19176            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
19177            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
19178        }
19179
19180        PackageSetting uninstalledPs = null;
19181        PackageParser.Package pkg = null;
19182
19183        // for the uninstall-updates case and restricted profiles, remember the per-
19184        // user handle installed state
19185        int[] allUsers;
19186        synchronized (mPackages) {
19187            uninstalledPs = mSettings.mPackages.get(packageName);
19188            if (uninstalledPs == null) {
19189                Slog.w(TAG, "Not removing non-existent package " + packageName);
19190                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19191            }
19192
19193            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
19194                    && uninstalledPs.versionCode != versionCode) {
19195                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
19196                        + uninstalledPs.versionCode + " != " + versionCode);
19197                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19198            }
19199
19200            // Static shared libs can be declared by any package, so let us not
19201            // allow removing a package if it provides a lib others depend on.
19202            pkg = mPackages.get(packageName);
19203
19204            allUsers = sUserManager.getUserIds();
19205
19206            if (pkg != null && pkg.staticSharedLibName != null) {
19207                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
19208                        pkg.staticSharedLibVersion);
19209                if (libEntry != null) {
19210                    for (int currUserId : allUsers) {
19211                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
19212                            continue;
19213                        }
19214                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
19215                                libEntry.info, 0, currUserId);
19216                        if (!ArrayUtils.isEmpty(libClientPackages)) {
19217                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
19218                                    + " hosting lib " + libEntry.info.getName() + " version "
19219                                    + libEntry.info.getVersion() + " used by " + libClientPackages
19220                                    + " for user " + currUserId);
19221                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
19222                        }
19223                    }
19224                }
19225            }
19226
19227            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
19228        }
19229
19230        final int freezeUser;
19231        if (isUpdatedSystemApp(uninstalledPs)
19232                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
19233            // We're downgrading a system app, which will apply to all users, so
19234            // freeze them all during the downgrade
19235            freezeUser = UserHandle.USER_ALL;
19236        } else {
19237            freezeUser = removeUser;
19238        }
19239
19240        synchronized (mInstallLock) {
19241            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
19242            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
19243                    deleteFlags, "deletePackageX")) {
19244                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
19245                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
19246            }
19247            synchronized (mPackages) {
19248                if (res) {
19249                    if (pkg != null) {
19250                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
19251                    }
19252                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
19253                    updateInstantAppInstallerLocked(packageName);
19254                }
19255            }
19256        }
19257
19258        if (res) {
19259            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
19260            info.sendPackageRemovedBroadcasts(killApp);
19261            info.sendSystemPackageUpdatedBroadcasts();
19262            info.sendSystemPackageAppearedBroadcasts();
19263        }
19264        // Force a gc here.
19265        Runtime.getRuntime().gc();
19266        // Delete the resources here after sending the broadcast to let
19267        // other processes clean up before deleting resources.
19268        if (info.args != null) {
19269            synchronized (mInstallLock) {
19270                info.args.doPostDeleteLI(true);
19271            }
19272        }
19273
19274        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
19275    }
19276
19277    static class PackageRemovedInfo {
19278        final PackageSender packageSender;
19279        String removedPackage;
19280        String installerPackageName;
19281        int uid = -1;
19282        int removedAppId = -1;
19283        int[] origUsers;
19284        int[] removedUsers = null;
19285        int[] broadcastUsers = null;
19286        SparseArray<Integer> installReasons;
19287        boolean isRemovedPackageSystemUpdate = false;
19288        boolean isUpdate;
19289        boolean dataRemoved;
19290        boolean removedForAllUsers;
19291        boolean isStaticSharedLib;
19292        // Clean up resources deleted packages.
19293        InstallArgs args = null;
19294        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
19295        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
19296
19297        PackageRemovedInfo(PackageSender packageSender) {
19298            this.packageSender = packageSender;
19299        }
19300
19301        void sendPackageRemovedBroadcasts(boolean killApp) {
19302            sendPackageRemovedBroadcastInternal(killApp);
19303            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
19304            for (int i = 0; i < childCount; i++) {
19305                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19306                childInfo.sendPackageRemovedBroadcastInternal(killApp);
19307            }
19308        }
19309
19310        void sendSystemPackageUpdatedBroadcasts() {
19311            if (isRemovedPackageSystemUpdate) {
19312                sendSystemPackageUpdatedBroadcastsInternal();
19313                final int childCount = (removedChildPackages != null)
19314                        ? removedChildPackages.size() : 0;
19315                for (int i = 0; i < childCount; i++) {
19316                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
19317                    if (childInfo.isRemovedPackageSystemUpdate) {
19318                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
19319                    }
19320                }
19321            }
19322        }
19323
19324        void sendSystemPackageAppearedBroadcasts() {
19325            final int packageCount = (appearedChildPackages != null)
19326                    ? appearedChildPackages.size() : 0;
19327            for (int i = 0; i < packageCount; i++) {
19328                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
19329                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
19330                    true /*sendBootCompleted*/, false /*startReceiver*/,
19331                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
19332            }
19333        }
19334
19335        private void sendSystemPackageUpdatedBroadcastsInternal() {
19336            Bundle extras = new Bundle(2);
19337            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
19338            extras.putBoolean(Intent.EXTRA_REPLACING, true);
19339            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19340                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19341            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19342                removedPackage, extras, 0, null /*targetPackage*/, null, null);
19343            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
19344                null, null, 0, removedPackage, null, null);
19345            if (installerPackageName != null) {
19346                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
19347                        removedPackage, extras, 0 /*flags*/,
19348                        installerPackageName, null, null);
19349                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19350                        removedPackage, extras, 0 /*flags*/,
19351                        installerPackageName, null, null);
19352            }
19353        }
19354
19355        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19356            // Don't send static shared library removal broadcasts as these
19357            // libs are visible only the the apps that depend on them an one
19358            // cannot remove the library if it has a dependency.
19359            if (isStaticSharedLib) {
19360                return;
19361            }
19362            Bundle extras = new Bundle(2);
19363            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19364            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19365            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19366            if (isUpdate || isRemovedPackageSystemUpdate) {
19367                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19368            }
19369            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19370            if (removedPackage != null) {
19371                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19372                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19373                if (installerPackageName != null) {
19374                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19375                            removedPackage, extras, 0 /*flags*/,
19376                            installerPackageName, null, broadcastUsers);
19377                }
19378                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19379                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19380                        removedPackage, extras,
19381                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19382                        null, null, broadcastUsers);
19383                }
19384            }
19385            if (removedAppId >= 0) {
19386                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19387                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19388                    null, null, broadcastUsers);
19389            }
19390        }
19391
19392        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19393            removedUsers = userIds;
19394            if (removedUsers == null) {
19395                broadcastUsers = null;
19396                return;
19397            }
19398
19399            broadcastUsers = EMPTY_INT_ARRAY;
19400            for (int i = userIds.length - 1; i >= 0; --i) {
19401                final int userId = userIds[i];
19402                if (deletedPackageSetting.getInstantApp(userId)) {
19403                    continue;
19404                }
19405                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19406            }
19407        }
19408    }
19409
19410    /*
19411     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19412     * flag is not set, the data directory is removed as well.
19413     * make sure this flag is set for partially installed apps. If not its meaningless to
19414     * delete a partially installed application.
19415     */
19416    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19417            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19418        String packageName = ps.name;
19419        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19420        // Retrieve object to delete permissions for shared user later on
19421        final PackageParser.Package deletedPkg;
19422        final PackageSetting deletedPs;
19423        // reader
19424        synchronized (mPackages) {
19425            deletedPkg = mPackages.get(packageName);
19426            deletedPs = mSettings.mPackages.get(packageName);
19427            if (outInfo != null) {
19428                outInfo.removedPackage = packageName;
19429                outInfo.installerPackageName = ps.installerPackageName;
19430                outInfo.isStaticSharedLib = deletedPkg != null
19431                        && deletedPkg.staticSharedLibName != null;
19432                outInfo.populateUsers(deletedPs == null ? null
19433                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19434            }
19435        }
19436
19437        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19438
19439        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19440            final PackageParser.Package resolvedPkg;
19441            if (deletedPkg != null) {
19442                resolvedPkg = deletedPkg;
19443            } else {
19444                // We don't have a parsed package when it lives on an ejected
19445                // adopted storage device, so fake something together
19446                resolvedPkg = new PackageParser.Package(ps.name);
19447                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19448            }
19449            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19450                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19451            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19452            if (outInfo != null) {
19453                outInfo.dataRemoved = true;
19454            }
19455            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19456        }
19457
19458        int removedAppId = -1;
19459
19460        // writer
19461        synchronized (mPackages) {
19462            boolean installedStateChanged = false;
19463            if (deletedPs != null) {
19464                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19465                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19466                    clearDefaultBrowserIfNeeded(packageName);
19467                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19468                    removedAppId = mSettings.removePackageLPw(packageName);
19469                    if (outInfo != null) {
19470                        outInfo.removedAppId = removedAppId;
19471                    }
19472                    updatePermissionsLPw(deletedPs.name, null, 0);
19473                    if (deletedPs.sharedUser != null) {
19474                        // Remove permissions associated with package. Since runtime
19475                        // permissions are per user we have to kill the removed package
19476                        // or packages running under the shared user of the removed
19477                        // package if revoking the permissions requested only by the removed
19478                        // package is successful and this causes a change in gids.
19479                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19480                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19481                                    userId);
19482                            if (userIdToKill == UserHandle.USER_ALL
19483                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19484                                // If gids changed for this user, kill all affected packages.
19485                                mHandler.post(new Runnable() {
19486                                    @Override
19487                                    public void run() {
19488                                        // This has to happen with no lock held.
19489                                        killApplication(deletedPs.name, deletedPs.appId,
19490                                                KILL_APP_REASON_GIDS_CHANGED);
19491                                    }
19492                                });
19493                                break;
19494                            }
19495                        }
19496                    }
19497                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19498                }
19499                // make sure to preserve per-user disabled state if this removal was just
19500                // a downgrade of a system app to the factory package
19501                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19502                    if (DEBUG_REMOVE) {
19503                        Slog.d(TAG, "Propagating install state across downgrade");
19504                    }
19505                    for (int userId : allUserHandles) {
19506                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19507                        if (DEBUG_REMOVE) {
19508                            Slog.d(TAG, "    user " + userId + " => " + installed);
19509                        }
19510                        if (installed != ps.getInstalled(userId)) {
19511                            installedStateChanged = true;
19512                        }
19513                        ps.setInstalled(installed, userId);
19514                    }
19515                }
19516            }
19517            // can downgrade to reader
19518            if (writeSettings) {
19519                // Save settings now
19520                mSettings.writeLPr();
19521            }
19522            if (installedStateChanged) {
19523                mSettings.writeKernelMappingLPr(ps);
19524            }
19525        }
19526        if (removedAppId != -1) {
19527            // A user ID was deleted here. Go through all users and remove it
19528            // from KeyStore.
19529            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19530        }
19531    }
19532
19533    static boolean locationIsPrivileged(File path) {
19534        try {
19535            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19536                    .getCanonicalPath();
19537            return path.getCanonicalPath().startsWith(privilegedAppDir);
19538        } catch (IOException e) {
19539            Slog.e(TAG, "Unable to access code path " + path);
19540        }
19541        return false;
19542    }
19543
19544    /*
19545     * Tries to delete system package.
19546     */
19547    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19548            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19549            boolean writeSettings) {
19550        if (deletedPs.parentPackageName != null) {
19551            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19552            return false;
19553        }
19554
19555        final boolean applyUserRestrictions
19556                = (allUserHandles != null) && (outInfo.origUsers != null);
19557        final PackageSetting disabledPs;
19558        // Confirm if the system package has been updated
19559        // An updated system app can be deleted. This will also have to restore
19560        // the system pkg from system partition
19561        // reader
19562        synchronized (mPackages) {
19563            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19564        }
19565
19566        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19567                + " disabledPs=" + disabledPs);
19568
19569        if (disabledPs == null) {
19570            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19571            return false;
19572        } else if (DEBUG_REMOVE) {
19573            Slog.d(TAG, "Deleting system pkg from data partition");
19574        }
19575
19576        if (DEBUG_REMOVE) {
19577            if (applyUserRestrictions) {
19578                Slog.d(TAG, "Remembering install states:");
19579                for (int userId : allUserHandles) {
19580                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19581                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19582                }
19583            }
19584        }
19585
19586        // Delete the updated package
19587        outInfo.isRemovedPackageSystemUpdate = true;
19588        if (outInfo.removedChildPackages != null) {
19589            final int childCount = (deletedPs.childPackageNames != null)
19590                    ? deletedPs.childPackageNames.size() : 0;
19591            for (int i = 0; i < childCount; i++) {
19592                String childPackageName = deletedPs.childPackageNames.get(i);
19593                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19594                        .contains(childPackageName)) {
19595                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19596                            childPackageName);
19597                    if (childInfo != null) {
19598                        childInfo.isRemovedPackageSystemUpdate = true;
19599                    }
19600                }
19601            }
19602        }
19603
19604        if (disabledPs.versionCode < deletedPs.versionCode) {
19605            // Delete data for downgrades
19606            flags &= ~PackageManager.DELETE_KEEP_DATA;
19607        } else {
19608            // Preserve data by setting flag
19609            flags |= PackageManager.DELETE_KEEP_DATA;
19610        }
19611
19612        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19613                outInfo, writeSettings, disabledPs.pkg);
19614        if (!ret) {
19615            return false;
19616        }
19617
19618        // writer
19619        synchronized (mPackages) {
19620            // Reinstate the old system package
19621            enableSystemPackageLPw(disabledPs.pkg);
19622            // Remove any native libraries from the upgraded package.
19623            removeNativeBinariesLI(deletedPs);
19624        }
19625
19626        // Install the system package
19627        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19628        int parseFlags = mDefParseFlags
19629                | PackageParser.PARSE_MUST_BE_APK
19630                | PackageParser.PARSE_IS_SYSTEM
19631                | PackageParser.PARSE_IS_SYSTEM_DIR;
19632        if (locationIsPrivileged(disabledPs.codePath)) {
19633            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19634        }
19635
19636        final PackageParser.Package newPkg;
19637        try {
19638            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19639                0 /* currentTime */, null);
19640        } catch (PackageManagerException e) {
19641            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19642                    + e.getMessage());
19643            return false;
19644        }
19645
19646        try {
19647            // update shared libraries for the newly re-installed system package
19648            updateSharedLibrariesLPr(newPkg, null);
19649        } catch (PackageManagerException e) {
19650            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19651        }
19652
19653        prepareAppDataAfterInstallLIF(newPkg);
19654
19655        // writer
19656        synchronized (mPackages) {
19657            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19658
19659            // Propagate the permissions state as we do not want to drop on the floor
19660            // runtime permissions. The update permissions method below will take
19661            // care of removing obsolete permissions and grant install permissions.
19662            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19663            updatePermissionsLPw(newPkg.packageName, newPkg,
19664                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19665
19666            if (applyUserRestrictions) {
19667                boolean installedStateChanged = false;
19668                if (DEBUG_REMOVE) {
19669                    Slog.d(TAG, "Propagating install state across reinstall");
19670                }
19671                for (int userId : allUserHandles) {
19672                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19673                    if (DEBUG_REMOVE) {
19674                        Slog.d(TAG, "    user " + userId + " => " + installed);
19675                    }
19676                    if (installed != ps.getInstalled(userId)) {
19677                        installedStateChanged = true;
19678                    }
19679                    ps.setInstalled(installed, userId);
19680
19681                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19682                }
19683                // Regardless of writeSettings we need to ensure that this restriction
19684                // state propagation is persisted
19685                mSettings.writeAllUsersPackageRestrictionsLPr();
19686                if (installedStateChanged) {
19687                    mSettings.writeKernelMappingLPr(ps);
19688                }
19689            }
19690            // can downgrade to reader here
19691            if (writeSettings) {
19692                mSettings.writeLPr();
19693            }
19694        }
19695        return true;
19696    }
19697
19698    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19699            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19700            PackageRemovedInfo outInfo, boolean writeSettings,
19701            PackageParser.Package replacingPackage) {
19702        synchronized (mPackages) {
19703            if (outInfo != null) {
19704                outInfo.uid = ps.appId;
19705            }
19706
19707            if (outInfo != null && outInfo.removedChildPackages != null) {
19708                final int childCount = (ps.childPackageNames != null)
19709                        ? ps.childPackageNames.size() : 0;
19710                for (int i = 0; i < childCount; i++) {
19711                    String childPackageName = ps.childPackageNames.get(i);
19712                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19713                    if (childPs == null) {
19714                        return false;
19715                    }
19716                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19717                            childPackageName);
19718                    if (childInfo != null) {
19719                        childInfo.uid = childPs.appId;
19720                    }
19721                }
19722            }
19723        }
19724
19725        // Delete package data from internal structures and also remove data if flag is set
19726        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19727
19728        // Delete the child packages data
19729        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19730        for (int i = 0; i < childCount; i++) {
19731            PackageSetting childPs;
19732            synchronized (mPackages) {
19733                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19734            }
19735            if (childPs != null) {
19736                PackageRemovedInfo childOutInfo = (outInfo != null
19737                        && outInfo.removedChildPackages != null)
19738                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19739                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19740                        && (replacingPackage != null
19741                        && !replacingPackage.hasChildPackage(childPs.name))
19742                        ? flags & ~DELETE_KEEP_DATA : flags;
19743                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19744                        deleteFlags, writeSettings);
19745            }
19746        }
19747
19748        // Delete application code and resources only for parent packages
19749        if (ps.parentPackageName == null) {
19750            if (deleteCodeAndResources && (outInfo != null)) {
19751                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19752                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19753                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19754            }
19755        }
19756
19757        return true;
19758    }
19759
19760    @Override
19761    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19762            int userId) {
19763        mContext.enforceCallingOrSelfPermission(
19764                android.Manifest.permission.DELETE_PACKAGES, null);
19765        synchronized (mPackages) {
19766            // Cannot block uninstall of static shared libs as they are
19767            // considered a part of the using app (emulating static linking).
19768            // Also static libs are installed always on internal storage.
19769            PackageParser.Package pkg = mPackages.get(packageName);
19770            if (pkg != null && pkg.staticSharedLibName != null) {
19771                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19772                        + " providing static shared library: " + pkg.staticSharedLibName);
19773                return false;
19774            }
19775            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19776            mSettings.writePackageRestrictionsLPr(userId);
19777        }
19778        return true;
19779    }
19780
19781    @Override
19782    public boolean getBlockUninstallForUser(String packageName, int userId) {
19783        synchronized (mPackages) {
19784            final PackageSetting ps = mSettings.mPackages.get(packageName);
19785            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19786                return false;
19787            }
19788            return mSettings.getBlockUninstallLPr(userId, packageName);
19789        }
19790    }
19791
19792    @Override
19793    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19794        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19795        synchronized (mPackages) {
19796            PackageSetting ps = mSettings.mPackages.get(packageName);
19797            if (ps == null) {
19798                Log.w(TAG, "Package doesn't exist: " + packageName);
19799                return false;
19800            }
19801            if (systemUserApp) {
19802                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19803            } else {
19804                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19805            }
19806            mSettings.writeLPr();
19807        }
19808        return true;
19809    }
19810
19811    /*
19812     * This method handles package deletion in general
19813     */
19814    private boolean deletePackageLIF(String packageName, UserHandle user,
19815            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19816            PackageRemovedInfo outInfo, boolean writeSettings,
19817            PackageParser.Package replacingPackage) {
19818        if (packageName == null) {
19819            Slog.w(TAG, "Attempt to delete null packageName.");
19820            return false;
19821        }
19822
19823        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19824
19825        PackageSetting ps;
19826        synchronized (mPackages) {
19827            ps = mSettings.mPackages.get(packageName);
19828            if (ps == null) {
19829                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19830                return false;
19831            }
19832
19833            if (ps.parentPackageName != null && (!isSystemApp(ps)
19834                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19835                if (DEBUG_REMOVE) {
19836                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19837                            + ((user == null) ? UserHandle.USER_ALL : user));
19838                }
19839                final int removedUserId = (user != null) ? user.getIdentifier()
19840                        : UserHandle.USER_ALL;
19841                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19842                    return false;
19843                }
19844                markPackageUninstalledForUserLPw(ps, user);
19845                scheduleWritePackageRestrictionsLocked(user);
19846                return true;
19847            }
19848        }
19849
19850        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19851                && user.getIdentifier() != UserHandle.USER_ALL)) {
19852            // The caller is asking that the package only be deleted for a single
19853            // user.  To do this, we just mark its uninstalled state and delete
19854            // its data. If this is a system app, we only allow this to happen if
19855            // they have set the special DELETE_SYSTEM_APP which requests different
19856            // semantics than normal for uninstalling system apps.
19857            markPackageUninstalledForUserLPw(ps, user);
19858
19859            if (!isSystemApp(ps)) {
19860                // Do not uninstall the APK if an app should be cached
19861                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19862                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19863                    // Other user still have this package installed, so all
19864                    // we need to do is clear this user's data and save that
19865                    // it is uninstalled.
19866                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19867                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19868                        return false;
19869                    }
19870                    scheduleWritePackageRestrictionsLocked(user);
19871                    return true;
19872                } else {
19873                    // We need to set it back to 'installed' so the uninstall
19874                    // broadcasts will be sent correctly.
19875                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19876                    ps.setInstalled(true, user.getIdentifier());
19877                    mSettings.writeKernelMappingLPr(ps);
19878                }
19879            } else {
19880                // This is a system app, so we assume that the
19881                // other users still have this package installed, so all
19882                // we need to do is clear this user's data and save that
19883                // it is uninstalled.
19884                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19885                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19886                    return false;
19887                }
19888                scheduleWritePackageRestrictionsLocked(user);
19889                return true;
19890            }
19891        }
19892
19893        // If we are deleting a composite package for all users, keep track
19894        // of result for each child.
19895        if (ps.childPackageNames != null && outInfo != null) {
19896            synchronized (mPackages) {
19897                final int childCount = ps.childPackageNames.size();
19898                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19899                for (int i = 0; i < childCount; i++) {
19900                    String childPackageName = ps.childPackageNames.get(i);
19901                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19902                    childInfo.removedPackage = childPackageName;
19903                    childInfo.installerPackageName = ps.installerPackageName;
19904                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19905                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19906                    if (childPs != null) {
19907                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19908                    }
19909                }
19910            }
19911        }
19912
19913        boolean ret = false;
19914        if (isSystemApp(ps)) {
19915            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19916            // When an updated system application is deleted we delete the existing resources
19917            // as well and fall back to existing code in system partition
19918            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19919        } else {
19920            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19921            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19922                    outInfo, writeSettings, replacingPackage);
19923        }
19924
19925        // Take a note whether we deleted the package for all users
19926        if (outInfo != null) {
19927            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19928            if (outInfo.removedChildPackages != null) {
19929                synchronized (mPackages) {
19930                    final int childCount = outInfo.removedChildPackages.size();
19931                    for (int i = 0; i < childCount; i++) {
19932                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19933                        if (childInfo != null) {
19934                            childInfo.removedForAllUsers = mPackages.get(
19935                                    childInfo.removedPackage) == null;
19936                        }
19937                    }
19938                }
19939            }
19940            // If we uninstalled an update to a system app there may be some
19941            // child packages that appeared as they are declared in the system
19942            // app but were not declared in the update.
19943            if (isSystemApp(ps)) {
19944                synchronized (mPackages) {
19945                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19946                    final int childCount = (updatedPs.childPackageNames != null)
19947                            ? updatedPs.childPackageNames.size() : 0;
19948                    for (int i = 0; i < childCount; i++) {
19949                        String childPackageName = updatedPs.childPackageNames.get(i);
19950                        if (outInfo.removedChildPackages == null
19951                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19952                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19953                            if (childPs == null) {
19954                                continue;
19955                            }
19956                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19957                            installRes.name = childPackageName;
19958                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19959                            installRes.pkg = mPackages.get(childPackageName);
19960                            installRes.uid = childPs.pkg.applicationInfo.uid;
19961                            if (outInfo.appearedChildPackages == null) {
19962                                outInfo.appearedChildPackages = new ArrayMap<>();
19963                            }
19964                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19965                        }
19966                    }
19967                }
19968            }
19969        }
19970
19971        return ret;
19972    }
19973
19974    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19975        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19976                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19977        for (int nextUserId : userIds) {
19978            if (DEBUG_REMOVE) {
19979                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19980            }
19981            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19982                    false /*installed*/,
19983                    true /*stopped*/,
19984                    true /*notLaunched*/,
19985                    false /*hidden*/,
19986                    false /*suspended*/,
19987                    false /*instantApp*/,
19988                    null /*lastDisableAppCaller*/,
19989                    null /*enabledComponents*/,
19990                    null /*disabledComponents*/,
19991                    ps.readUserState(nextUserId).domainVerificationStatus,
19992                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19993        }
19994        mSettings.writeKernelMappingLPr(ps);
19995    }
19996
19997    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19998            PackageRemovedInfo outInfo) {
19999        final PackageParser.Package pkg;
20000        synchronized (mPackages) {
20001            pkg = mPackages.get(ps.name);
20002        }
20003
20004        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
20005                : new int[] {userId};
20006        for (int nextUserId : userIds) {
20007            if (DEBUG_REMOVE) {
20008                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
20009                        + nextUserId);
20010            }
20011
20012            destroyAppDataLIF(pkg, userId,
20013                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20014            destroyAppProfilesLIF(pkg, userId);
20015            clearDefaultBrowserIfNeededForUser(ps.name, userId);
20016            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
20017            schedulePackageCleaning(ps.name, nextUserId, false);
20018            synchronized (mPackages) {
20019                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
20020                    scheduleWritePackageRestrictionsLocked(nextUserId);
20021                }
20022                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
20023            }
20024        }
20025
20026        if (outInfo != null) {
20027            outInfo.removedPackage = ps.name;
20028            outInfo.installerPackageName = ps.installerPackageName;
20029            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
20030            outInfo.removedAppId = ps.appId;
20031            outInfo.removedUsers = userIds;
20032            outInfo.broadcastUsers = userIds;
20033        }
20034
20035        return true;
20036    }
20037
20038    private final class ClearStorageConnection implements ServiceConnection {
20039        IMediaContainerService mContainerService;
20040
20041        @Override
20042        public void onServiceConnected(ComponentName name, IBinder service) {
20043            synchronized (this) {
20044                mContainerService = IMediaContainerService.Stub
20045                        .asInterface(Binder.allowBlocking(service));
20046                notifyAll();
20047            }
20048        }
20049
20050        @Override
20051        public void onServiceDisconnected(ComponentName name) {
20052        }
20053    }
20054
20055    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
20056        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
20057
20058        final boolean mounted;
20059        if (Environment.isExternalStorageEmulated()) {
20060            mounted = true;
20061        } else {
20062            final String status = Environment.getExternalStorageState();
20063
20064            mounted = status.equals(Environment.MEDIA_MOUNTED)
20065                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
20066        }
20067
20068        if (!mounted) {
20069            return;
20070        }
20071
20072        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
20073        int[] users;
20074        if (userId == UserHandle.USER_ALL) {
20075            users = sUserManager.getUserIds();
20076        } else {
20077            users = new int[] { userId };
20078        }
20079        final ClearStorageConnection conn = new ClearStorageConnection();
20080        if (mContext.bindServiceAsUser(
20081                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
20082            try {
20083                for (int curUser : users) {
20084                    long timeout = SystemClock.uptimeMillis() + 5000;
20085                    synchronized (conn) {
20086                        long now;
20087                        while (conn.mContainerService == null &&
20088                                (now = SystemClock.uptimeMillis()) < timeout) {
20089                            try {
20090                                conn.wait(timeout - now);
20091                            } catch (InterruptedException e) {
20092                            }
20093                        }
20094                    }
20095                    if (conn.mContainerService == null) {
20096                        return;
20097                    }
20098
20099                    final UserEnvironment userEnv = new UserEnvironment(curUser);
20100                    clearDirectory(conn.mContainerService,
20101                            userEnv.buildExternalStorageAppCacheDirs(packageName));
20102                    if (allData) {
20103                        clearDirectory(conn.mContainerService,
20104                                userEnv.buildExternalStorageAppDataDirs(packageName));
20105                        clearDirectory(conn.mContainerService,
20106                                userEnv.buildExternalStorageAppMediaDirs(packageName));
20107                    }
20108                }
20109            } finally {
20110                mContext.unbindService(conn);
20111            }
20112        }
20113    }
20114
20115    @Override
20116    public void clearApplicationProfileData(String packageName) {
20117        enforceSystemOrRoot("Only the system can clear all profile data");
20118
20119        final PackageParser.Package pkg;
20120        synchronized (mPackages) {
20121            pkg = mPackages.get(packageName);
20122        }
20123
20124        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
20125            synchronized (mInstallLock) {
20126                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
20127            }
20128        }
20129    }
20130
20131    @Override
20132    public void clearApplicationUserData(final String packageName,
20133            final IPackageDataObserver observer, final int userId) {
20134        mContext.enforceCallingOrSelfPermission(
20135                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
20136
20137        final int callingUid = Binder.getCallingUid();
20138        enforceCrossUserPermission(callingUid, userId,
20139                true /* requireFullPermission */, false /* checkShell */, "clear application data");
20140
20141        final PackageSetting ps = mSettings.getPackageLPr(packageName);
20142        if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
20143            return;
20144        }
20145        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
20146            throw new SecurityException("Cannot clear data for a protected package: "
20147                    + packageName);
20148        }
20149        // Queue up an async operation since the package deletion may take a little while.
20150        mHandler.post(new Runnable() {
20151            public void run() {
20152                mHandler.removeCallbacks(this);
20153                final boolean succeeded;
20154                try (PackageFreezer freezer = freezePackage(packageName,
20155                        "clearApplicationUserData")) {
20156                    synchronized (mInstallLock) {
20157                        succeeded = clearApplicationUserDataLIF(packageName, userId);
20158                    }
20159                    clearExternalStorageDataSync(packageName, userId, true);
20160                    synchronized (mPackages) {
20161                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
20162                                packageName, userId);
20163                    }
20164                }
20165                if (succeeded) {
20166                    // invoke DeviceStorageMonitor's update method to clear any notifications
20167                    DeviceStorageMonitorInternal dsm = LocalServices
20168                            .getService(DeviceStorageMonitorInternal.class);
20169                    if (dsm != null) {
20170                        dsm.checkMemory();
20171                    }
20172                }
20173                if(observer != null) {
20174                    try {
20175                        observer.onRemoveCompleted(packageName, succeeded);
20176                    } catch (RemoteException e) {
20177                        Log.i(TAG, "Observer no longer exists.");
20178                    }
20179                } //end if observer
20180            } //end run
20181        });
20182    }
20183
20184    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
20185        if (packageName == null) {
20186            Slog.w(TAG, "Attempt to delete null packageName.");
20187            return false;
20188        }
20189
20190        // Try finding details about the requested package
20191        PackageParser.Package pkg;
20192        synchronized (mPackages) {
20193            pkg = mPackages.get(packageName);
20194            if (pkg == null) {
20195                final PackageSetting ps = mSettings.mPackages.get(packageName);
20196                if (ps != null) {
20197                    pkg = ps.pkg;
20198                }
20199            }
20200
20201            if (pkg == null) {
20202                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
20203                return false;
20204            }
20205
20206            PackageSetting ps = (PackageSetting) pkg.mExtras;
20207            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20208        }
20209
20210        clearAppDataLIF(pkg, userId,
20211                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
20212
20213        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20214        removeKeystoreDataIfNeeded(userId, appId);
20215
20216        UserManagerInternal umInternal = getUserManagerInternal();
20217        final int flags;
20218        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
20219            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
20220        } else if (umInternal.isUserRunning(userId)) {
20221            flags = StorageManager.FLAG_STORAGE_DE;
20222        } else {
20223            flags = 0;
20224        }
20225        prepareAppDataContentsLIF(pkg, userId, flags);
20226
20227        return true;
20228    }
20229
20230    /**
20231     * Reverts user permission state changes (permissions and flags) in
20232     * all packages for a given user.
20233     *
20234     * @param userId The device user for which to do a reset.
20235     */
20236    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
20237        final int packageCount = mPackages.size();
20238        for (int i = 0; i < packageCount; i++) {
20239            PackageParser.Package pkg = mPackages.valueAt(i);
20240            PackageSetting ps = (PackageSetting) pkg.mExtras;
20241            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
20242        }
20243    }
20244
20245    private void resetNetworkPolicies(int userId) {
20246        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
20247    }
20248
20249    /**
20250     * Reverts user permission state changes (permissions and flags).
20251     *
20252     * @param ps The package for which to reset.
20253     * @param userId The device user for which to do a reset.
20254     */
20255    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
20256            final PackageSetting ps, final int userId) {
20257        if (ps.pkg == null) {
20258            return;
20259        }
20260
20261        // These are flags that can change base on user actions.
20262        final int userSettableMask = FLAG_PERMISSION_USER_SET
20263                | FLAG_PERMISSION_USER_FIXED
20264                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
20265                | FLAG_PERMISSION_REVIEW_REQUIRED;
20266
20267        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
20268                | FLAG_PERMISSION_POLICY_FIXED;
20269
20270        boolean writeInstallPermissions = false;
20271        boolean writeRuntimePermissions = false;
20272
20273        final int permissionCount = ps.pkg.requestedPermissions.size();
20274        for (int i = 0; i < permissionCount; i++) {
20275            String permission = ps.pkg.requestedPermissions.get(i);
20276
20277            BasePermission bp = mSettings.mPermissions.get(permission);
20278            if (bp == null) {
20279                continue;
20280            }
20281
20282            // If shared user we just reset the state to which only this app contributed.
20283            if (ps.sharedUser != null) {
20284                boolean used = false;
20285                final int packageCount = ps.sharedUser.packages.size();
20286                for (int j = 0; j < packageCount; j++) {
20287                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
20288                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
20289                            && pkg.pkg.requestedPermissions.contains(permission)) {
20290                        used = true;
20291                        break;
20292                    }
20293                }
20294                if (used) {
20295                    continue;
20296                }
20297            }
20298
20299            PermissionsState permissionsState = ps.getPermissionsState();
20300
20301            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
20302
20303            // Always clear the user settable flags.
20304            final boolean hasInstallState = permissionsState.getInstallPermissionState(
20305                    bp.name) != null;
20306            // If permission review is enabled and this is a legacy app, mark the
20307            // permission as requiring a review as this is the initial state.
20308            int flags = 0;
20309            if (mPermissionReviewRequired
20310                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
20311                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
20312            }
20313            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
20314                if (hasInstallState) {
20315                    writeInstallPermissions = true;
20316                } else {
20317                    writeRuntimePermissions = true;
20318                }
20319            }
20320
20321            // Below is only runtime permission handling.
20322            if (!bp.isRuntime()) {
20323                continue;
20324            }
20325
20326            // Never clobber system or policy.
20327            if ((oldFlags & policyOrSystemFlags) != 0) {
20328                continue;
20329            }
20330
20331            // If this permission was granted by default, make sure it is.
20332            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
20333                if (permissionsState.grantRuntimePermission(bp, userId)
20334                        != PERMISSION_OPERATION_FAILURE) {
20335                    writeRuntimePermissions = true;
20336                }
20337            // If permission review is enabled the permissions for a legacy apps
20338            // are represented as constantly granted runtime ones, so don't revoke.
20339            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
20340                // Otherwise, reset the permission.
20341                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
20342                switch (revokeResult) {
20343                    case PERMISSION_OPERATION_SUCCESS:
20344                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
20345                        writeRuntimePermissions = true;
20346                        final int appId = ps.appId;
20347                        mHandler.post(new Runnable() {
20348                            @Override
20349                            public void run() {
20350                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20351                            }
20352                        });
20353                    } break;
20354                }
20355            }
20356        }
20357
20358        // Synchronously write as we are taking permissions away.
20359        if (writeRuntimePermissions) {
20360            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20361        }
20362
20363        // Synchronously write as we are taking permissions away.
20364        if (writeInstallPermissions) {
20365            mSettings.writeLPr();
20366        }
20367    }
20368
20369    /**
20370     * Remove entries from the keystore daemon. Will only remove it if the
20371     * {@code appId} is valid.
20372     */
20373    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20374        if (appId < 0) {
20375            return;
20376        }
20377
20378        final KeyStore keyStore = KeyStore.getInstance();
20379        if (keyStore != null) {
20380            if (userId == UserHandle.USER_ALL) {
20381                for (final int individual : sUserManager.getUserIds()) {
20382                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20383                }
20384            } else {
20385                keyStore.clearUid(UserHandle.getUid(userId, appId));
20386            }
20387        } else {
20388            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20389        }
20390    }
20391
20392    @Override
20393    public void deleteApplicationCacheFiles(final String packageName,
20394            final IPackageDataObserver observer) {
20395        final int userId = UserHandle.getCallingUserId();
20396        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20397    }
20398
20399    @Override
20400    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20401            final IPackageDataObserver observer) {
20402        final int callingUid = Binder.getCallingUid();
20403        mContext.enforceCallingOrSelfPermission(
20404                android.Manifest.permission.DELETE_CACHE_FILES, null);
20405        enforceCrossUserPermission(callingUid, userId,
20406                /* requireFullPermission= */ true, /* checkShell= */ false,
20407                "delete application cache files");
20408        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20409                android.Manifest.permission.ACCESS_INSTANT_APPS);
20410
20411        final PackageParser.Package pkg;
20412        synchronized (mPackages) {
20413            pkg = mPackages.get(packageName);
20414        }
20415
20416        // Queue up an async operation since the package deletion may take a little while.
20417        mHandler.post(new Runnable() {
20418            public void run() {
20419                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20420                boolean doClearData = true;
20421                if (ps != null) {
20422                    final boolean targetIsInstantApp =
20423                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20424                    doClearData = !targetIsInstantApp
20425                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20426                }
20427                if (doClearData) {
20428                    synchronized (mInstallLock) {
20429                        final int flags = StorageManager.FLAG_STORAGE_DE
20430                                | StorageManager.FLAG_STORAGE_CE;
20431                        // We're only clearing cache files, so we don't care if the
20432                        // app is unfrozen and still able to run
20433                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20434                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20435                    }
20436                    clearExternalStorageDataSync(packageName, userId, false);
20437                }
20438                if (observer != null) {
20439                    try {
20440                        observer.onRemoveCompleted(packageName, true);
20441                    } catch (RemoteException e) {
20442                        Log.i(TAG, "Observer no longer exists.");
20443                    }
20444                }
20445            }
20446        });
20447    }
20448
20449    @Override
20450    public void getPackageSizeInfo(final String packageName, int userHandle,
20451            final IPackageStatsObserver observer) {
20452        throw new UnsupportedOperationException(
20453                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20454    }
20455
20456    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20457        final PackageSetting ps;
20458        synchronized (mPackages) {
20459            ps = mSettings.mPackages.get(packageName);
20460            if (ps == null) {
20461                Slog.w(TAG, "Failed to find settings for " + packageName);
20462                return false;
20463            }
20464        }
20465
20466        final String[] packageNames = { packageName };
20467        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20468        final String[] codePaths = { ps.codePathString };
20469
20470        try {
20471            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20472                    ps.appId, ceDataInodes, codePaths, stats);
20473
20474            // For now, ignore code size of packages on system partition
20475            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20476                stats.codeSize = 0;
20477            }
20478
20479            // External clients expect these to be tracked separately
20480            stats.dataSize -= stats.cacheSize;
20481
20482        } catch (InstallerException e) {
20483            Slog.w(TAG, String.valueOf(e));
20484            return false;
20485        }
20486
20487        return true;
20488    }
20489
20490    private int getUidTargetSdkVersionLockedLPr(int uid) {
20491        Object obj = mSettings.getUserIdLPr(uid);
20492        if (obj instanceof SharedUserSetting) {
20493            final SharedUserSetting sus = (SharedUserSetting) obj;
20494            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20495            final Iterator<PackageSetting> it = sus.packages.iterator();
20496            while (it.hasNext()) {
20497                final PackageSetting ps = it.next();
20498                if (ps.pkg != null) {
20499                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20500                    if (v < vers) vers = v;
20501                }
20502            }
20503            return vers;
20504        } else if (obj instanceof PackageSetting) {
20505            final PackageSetting ps = (PackageSetting) obj;
20506            if (ps.pkg != null) {
20507                return ps.pkg.applicationInfo.targetSdkVersion;
20508            }
20509        }
20510        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20511    }
20512
20513    @Override
20514    public void addPreferredActivity(IntentFilter filter, int match,
20515            ComponentName[] set, ComponentName activity, int userId) {
20516        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20517                "Adding preferred");
20518    }
20519
20520    private void addPreferredActivityInternal(IntentFilter filter, int match,
20521            ComponentName[] set, ComponentName activity, boolean always, int userId,
20522            String opname) {
20523        // writer
20524        int callingUid = Binder.getCallingUid();
20525        enforceCrossUserPermission(callingUid, userId,
20526                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20527        if (filter.countActions() == 0) {
20528            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20529            return;
20530        }
20531        synchronized (mPackages) {
20532            if (mContext.checkCallingOrSelfPermission(
20533                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20534                    != PackageManager.PERMISSION_GRANTED) {
20535                if (getUidTargetSdkVersionLockedLPr(callingUid)
20536                        < Build.VERSION_CODES.FROYO) {
20537                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20538                            + callingUid);
20539                    return;
20540                }
20541                mContext.enforceCallingOrSelfPermission(
20542                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20543            }
20544
20545            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20546            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20547                    + userId + ":");
20548            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20549            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20550            scheduleWritePackageRestrictionsLocked(userId);
20551            postPreferredActivityChangedBroadcast(userId);
20552        }
20553    }
20554
20555    private void postPreferredActivityChangedBroadcast(int userId) {
20556        mHandler.post(() -> {
20557            final IActivityManager am = ActivityManager.getService();
20558            if (am == null) {
20559                return;
20560            }
20561
20562            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20563            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20564            try {
20565                am.broadcastIntent(null, intent, null, null,
20566                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20567                        null, false, false, userId);
20568            } catch (RemoteException e) {
20569            }
20570        });
20571    }
20572
20573    @Override
20574    public void replacePreferredActivity(IntentFilter filter, int match,
20575            ComponentName[] set, ComponentName activity, int userId) {
20576        if (filter.countActions() != 1) {
20577            throw new IllegalArgumentException(
20578                    "replacePreferredActivity expects filter to have only 1 action.");
20579        }
20580        if (filter.countDataAuthorities() != 0
20581                || filter.countDataPaths() != 0
20582                || filter.countDataSchemes() > 1
20583                || filter.countDataTypes() != 0) {
20584            throw new IllegalArgumentException(
20585                    "replacePreferredActivity expects filter to have no data authorities, " +
20586                    "paths, or types; and at most one scheme.");
20587        }
20588
20589        final int callingUid = Binder.getCallingUid();
20590        enforceCrossUserPermission(callingUid, userId,
20591                true /* requireFullPermission */, false /* checkShell */,
20592                "replace preferred activity");
20593        synchronized (mPackages) {
20594            if (mContext.checkCallingOrSelfPermission(
20595                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20596                    != PackageManager.PERMISSION_GRANTED) {
20597                if (getUidTargetSdkVersionLockedLPr(callingUid)
20598                        < Build.VERSION_CODES.FROYO) {
20599                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20600                            + Binder.getCallingUid());
20601                    return;
20602                }
20603                mContext.enforceCallingOrSelfPermission(
20604                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20605            }
20606
20607            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20608            if (pir != null) {
20609                // Get all of the existing entries that exactly match this filter.
20610                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20611                if (existing != null && existing.size() == 1) {
20612                    PreferredActivity cur = existing.get(0);
20613                    if (DEBUG_PREFERRED) {
20614                        Slog.i(TAG, "Checking replace of preferred:");
20615                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20616                        if (!cur.mPref.mAlways) {
20617                            Slog.i(TAG, "  -- CUR; not mAlways!");
20618                        } else {
20619                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20620                            Slog.i(TAG, "  -- CUR: mSet="
20621                                    + Arrays.toString(cur.mPref.mSetComponents));
20622                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20623                            Slog.i(TAG, "  -- NEW: mMatch="
20624                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20625                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20626                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20627                        }
20628                    }
20629                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20630                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20631                            && cur.mPref.sameSet(set)) {
20632                        // Setting the preferred activity to what it happens to be already
20633                        if (DEBUG_PREFERRED) {
20634                            Slog.i(TAG, "Replacing with same preferred activity "
20635                                    + cur.mPref.mShortComponent + " for user "
20636                                    + userId + ":");
20637                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20638                        }
20639                        return;
20640                    }
20641                }
20642
20643                if (existing != null) {
20644                    if (DEBUG_PREFERRED) {
20645                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20646                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20647                    }
20648                    for (int i = 0; i < existing.size(); i++) {
20649                        PreferredActivity pa = existing.get(i);
20650                        if (DEBUG_PREFERRED) {
20651                            Slog.i(TAG, "Removing existing preferred activity "
20652                                    + pa.mPref.mComponent + ":");
20653                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20654                        }
20655                        pir.removeFilter(pa);
20656                    }
20657                }
20658            }
20659            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20660                    "Replacing preferred");
20661        }
20662    }
20663
20664    @Override
20665    public void clearPackagePreferredActivities(String packageName) {
20666        final int callingUid = Binder.getCallingUid();
20667        if (getInstantAppPackageName(callingUid) != null) {
20668            return;
20669        }
20670        // writer
20671        synchronized (mPackages) {
20672            PackageParser.Package pkg = mPackages.get(packageName);
20673            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20674                if (mContext.checkCallingOrSelfPermission(
20675                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20676                        != PackageManager.PERMISSION_GRANTED) {
20677                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20678                            < Build.VERSION_CODES.FROYO) {
20679                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20680                                + callingUid);
20681                        return;
20682                    }
20683                    mContext.enforceCallingOrSelfPermission(
20684                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20685                }
20686            }
20687            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20688            if (ps != null
20689                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20690                return;
20691            }
20692            int user = UserHandle.getCallingUserId();
20693            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20694                scheduleWritePackageRestrictionsLocked(user);
20695            }
20696        }
20697    }
20698
20699    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20700    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20701        ArrayList<PreferredActivity> removed = null;
20702        boolean changed = false;
20703        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20704            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20705            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20706            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20707                continue;
20708            }
20709            Iterator<PreferredActivity> it = pir.filterIterator();
20710            while (it.hasNext()) {
20711                PreferredActivity pa = it.next();
20712                // Mark entry for removal only if it matches the package name
20713                // and the entry is of type "always".
20714                if (packageName == null ||
20715                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20716                                && pa.mPref.mAlways)) {
20717                    if (removed == null) {
20718                        removed = new ArrayList<PreferredActivity>();
20719                    }
20720                    removed.add(pa);
20721                }
20722            }
20723            if (removed != null) {
20724                for (int j=0; j<removed.size(); j++) {
20725                    PreferredActivity pa = removed.get(j);
20726                    pir.removeFilter(pa);
20727                }
20728                changed = true;
20729            }
20730        }
20731        if (changed) {
20732            postPreferredActivityChangedBroadcast(userId);
20733        }
20734        return changed;
20735    }
20736
20737    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20738    private void clearIntentFilterVerificationsLPw(int userId) {
20739        final int packageCount = mPackages.size();
20740        for (int i = 0; i < packageCount; i++) {
20741            PackageParser.Package pkg = mPackages.valueAt(i);
20742            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20743        }
20744    }
20745
20746    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20747    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20748        if (userId == UserHandle.USER_ALL) {
20749            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20750                    sUserManager.getUserIds())) {
20751                for (int oneUserId : sUserManager.getUserIds()) {
20752                    scheduleWritePackageRestrictionsLocked(oneUserId);
20753                }
20754            }
20755        } else {
20756            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20757                scheduleWritePackageRestrictionsLocked(userId);
20758            }
20759        }
20760    }
20761
20762    /** Clears state for all users, and touches intent filter verification policy */
20763    void clearDefaultBrowserIfNeeded(String packageName) {
20764        for (int oneUserId : sUserManager.getUserIds()) {
20765            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20766        }
20767    }
20768
20769    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20770        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20771        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20772            if (packageName.equals(defaultBrowserPackageName)) {
20773                setDefaultBrowserPackageName(null, userId);
20774            }
20775        }
20776    }
20777
20778    @Override
20779    public void resetApplicationPreferences(int userId) {
20780        mContext.enforceCallingOrSelfPermission(
20781                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20782        final long identity = Binder.clearCallingIdentity();
20783        // writer
20784        try {
20785            synchronized (mPackages) {
20786                clearPackagePreferredActivitiesLPw(null, userId);
20787                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20788                // TODO: We have to reset the default SMS and Phone. This requires
20789                // significant refactoring to keep all default apps in the package
20790                // manager (cleaner but more work) or have the services provide
20791                // callbacks to the package manager to request a default app reset.
20792                applyFactoryDefaultBrowserLPw(userId);
20793                clearIntentFilterVerificationsLPw(userId);
20794                primeDomainVerificationsLPw(userId);
20795                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20796                scheduleWritePackageRestrictionsLocked(userId);
20797            }
20798            resetNetworkPolicies(userId);
20799        } finally {
20800            Binder.restoreCallingIdentity(identity);
20801        }
20802    }
20803
20804    @Override
20805    public int getPreferredActivities(List<IntentFilter> outFilters,
20806            List<ComponentName> outActivities, String packageName) {
20807        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20808            return 0;
20809        }
20810        int num = 0;
20811        final int userId = UserHandle.getCallingUserId();
20812        // reader
20813        synchronized (mPackages) {
20814            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20815            if (pir != null) {
20816                final Iterator<PreferredActivity> it = pir.filterIterator();
20817                while (it.hasNext()) {
20818                    final PreferredActivity pa = it.next();
20819                    if (packageName == null
20820                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20821                                    && pa.mPref.mAlways)) {
20822                        if (outFilters != null) {
20823                            outFilters.add(new IntentFilter(pa));
20824                        }
20825                        if (outActivities != null) {
20826                            outActivities.add(pa.mPref.mComponent);
20827                        }
20828                    }
20829                }
20830            }
20831        }
20832
20833        return num;
20834    }
20835
20836    @Override
20837    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20838            int userId) {
20839        int callingUid = Binder.getCallingUid();
20840        if (callingUid != Process.SYSTEM_UID) {
20841            throw new SecurityException(
20842                    "addPersistentPreferredActivity can only be run by the system");
20843        }
20844        if (filter.countActions() == 0) {
20845            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20846            return;
20847        }
20848        synchronized (mPackages) {
20849            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20850                    ":");
20851            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20852            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20853                    new PersistentPreferredActivity(filter, activity));
20854            scheduleWritePackageRestrictionsLocked(userId);
20855            postPreferredActivityChangedBroadcast(userId);
20856        }
20857    }
20858
20859    @Override
20860    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20861        int callingUid = Binder.getCallingUid();
20862        if (callingUid != Process.SYSTEM_UID) {
20863            throw new SecurityException(
20864                    "clearPackagePersistentPreferredActivities can only be run by the system");
20865        }
20866        ArrayList<PersistentPreferredActivity> removed = null;
20867        boolean changed = false;
20868        synchronized (mPackages) {
20869            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20870                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20871                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20872                        .valueAt(i);
20873                if (userId != thisUserId) {
20874                    continue;
20875                }
20876                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20877                while (it.hasNext()) {
20878                    PersistentPreferredActivity ppa = it.next();
20879                    // Mark entry for removal only if it matches the package name.
20880                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20881                        if (removed == null) {
20882                            removed = new ArrayList<PersistentPreferredActivity>();
20883                        }
20884                        removed.add(ppa);
20885                    }
20886                }
20887                if (removed != null) {
20888                    for (int j=0; j<removed.size(); j++) {
20889                        PersistentPreferredActivity ppa = removed.get(j);
20890                        ppir.removeFilter(ppa);
20891                    }
20892                    changed = true;
20893                }
20894            }
20895
20896            if (changed) {
20897                scheduleWritePackageRestrictionsLocked(userId);
20898                postPreferredActivityChangedBroadcast(userId);
20899            }
20900        }
20901    }
20902
20903    /**
20904     * Common machinery for picking apart a restored XML blob and passing
20905     * it to a caller-supplied functor to be applied to the running system.
20906     */
20907    private void restoreFromXml(XmlPullParser parser, int userId,
20908            String expectedStartTag, BlobXmlRestorer functor)
20909            throws IOException, XmlPullParserException {
20910        int type;
20911        while ((type = parser.next()) != XmlPullParser.START_TAG
20912                && type != XmlPullParser.END_DOCUMENT) {
20913        }
20914        if (type != XmlPullParser.START_TAG) {
20915            // oops didn't find a start tag?!
20916            if (DEBUG_BACKUP) {
20917                Slog.e(TAG, "Didn't find start tag during restore");
20918            }
20919            return;
20920        }
20921Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20922        // this is supposed to be TAG_PREFERRED_BACKUP
20923        if (!expectedStartTag.equals(parser.getName())) {
20924            if (DEBUG_BACKUP) {
20925                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20926            }
20927            return;
20928        }
20929
20930        // skip interfering stuff, then we're aligned with the backing implementation
20931        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20932Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20933        functor.apply(parser, userId);
20934    }
20935
20936    private interface BlobXmlRestorer {
20937        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20938    }
20939
20940    /**
20941     * Non-Binder method, support for the backup/restore mechanism: write the
20942     * full set of preferred activities in its canonical XML format.  Returns the
20943     * XML output as a byte array, or null if there is none.
20944     */
20945    @Override
20946    public byte[] getPreferredActivityBackup(int userId) {
20947        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20948            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20949        }
20950
20951        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20952        try {
20953            final XmlSerializer serializer = new FastXmlSerializer();
20954            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20955            serializer.startDocument(null, true);
20956            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20957
20958            synchronized (mPackages) {
20959                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20960            }
20961
20962            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20963            serializer.endDocument();
20964            serializer.flush();
20965        } catch (Exception e) {
20966            if (DEBUG_BACKUP) {
20967                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20968            }
20969            return null;
20970        }
20971
20972        return dataStream.toByteArray();
20973    }
20974
20975    @Override
20976    public void restorePreferredActivities(byte[] backup, int userId) {
20977        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20978            throw new SecurityException("Only the system may call restorePreferredActivities()");
20979        }
20980
20981        try {
20982            final XmlPullParser parser = Xml.newPullParser();
20983            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20984            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20985                    new BlobXmlRestorer() {
20986                        @Override
20987                        public void apply(XmlPullParser parser, int userId)
20988                                throws XmlPullParserException, IOException {
20989                            synchronized (mPackages) {
20990                                mSettings.readPreferredActivitiesLPw(parser, userId);
20991                            }
20992                        }
20993                    } );
20994        } catch (Exception e) {
20995            if (DEBUG_BACKUP) {
20996                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20997            }
20998        }
20999    }
21000
21001    /**
21002     * Non-Binder method, support for the backup/restore mechanism: write the
21003     * default browser (etc) settings in its canonical XML format.  Returns the default
21004     * browser XML representation as a byte array, or null if there is none.
21005     */
21006    @Override
21007    public byte[] getDefaultAppsBackup(int userId) {
21008        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21009            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
21010        }
21011
21012        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21013        try {
21014            final XmlSerializer serializer = new FastXmlSerializer();
21015            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21016            serializer.startDocument(null, true);
21017            serializer.startTag(null, TAG_DEFAULT_APPS);
21018
21019            synchronized (mPackages) {
21020                mSettings.writeDefaultAppsLPr(serializer, userId);
21021            }
21022
21023            serializer.endTag(null, TAG_DEFAULT_APPS);
21024            serializer.endDocument();
21025            serializer.flush();
21026        } catch (Exception e) {
21027            if (DEBUG_BACKUP) {
21028                Slog.e(TAG, "Unable to write default apps for backup", e);
21029            }
21030            return null;
21031        }
21032
21033        return dataStream.toByteArray();
21034    }
21035
21036    @Override
21037    public void restoreDefaultApps(byte[] backup, int userId) {
21038        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21039            throw new SecurityException("Only the system may call restoreDefaultApps()");
21040        }
21041
21042        try {
21043            final XmlPullParser parser = Xml.newPullParser();
21044            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21045            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
21046                    new BlobXmlRestorer() {
21047                        @Override
21048                        public void apply(XmlPullParser parser, int userId)
21049                                throws XmlPullParserException, IOException {
21050                            synchronized (mPackages) {
21051                                mSettings.readDefaultAppsLPw(parser, userId);
21052                            }
21053                        }
21054                    } );
21055        } catch (Exception e) {
21056            if (DEBUG_BACKUP) {
21057                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
21058            }
21059        }
21060    }
21061
21062    @Override
21063    public byte[] getIntentFilterVerificationBackup(int userId) {
21064        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21065            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
21066        }
21067
21068        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21069        try {
21070            final XmlSerializer serializer = new FastXmlSerializer();
21071            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21072            serializer.startDocument(null, true);
21073            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
21074
21075            synchronized (mPackages) {
21076                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
21077            }
21078
21079            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
21080            serializer.endDocument();
21081            serializer.flush();
21082        } catch (Exception e) {
21083            if (DEBUG_BACKUP) {
21084                Slog.e(TAG, "Unable to write default apps for backup", e);
21085            }
21086            return null;
21087        }
21088
21089        return dataStream.toByteArray();
21090    }
21091
21092    @Override
21093    public void restoreIntentFilterVerification(byte[] backup, int userId) {
21094        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21095            throw new SecurityException("Only the system may call restorePreferredActivities()");
21096        }
21097
21098        try {
21099            final XmlPullParser parser = Xml.newPullParser();
21100            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21101            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
21102                    new BlobXmlRestorer() {
21103                        @Override
21104                        public void apply(XmlPullParser parser, int userId)
21105                                throws XmlPullParserException, IOException {
21106                            synchronized (mPackages) {
21107                                mSettings.readAllDomainVerificationsLPr(parser, userId);
21108                                mSettings.writeLPr();
21109                            }
21110                        }
21111                    } );
21112        } catch (Exception e) {
21113            if (DEBUG_BACKUP) {
21114                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21115            }
21116        }
21117    }
21118
21119    @Override
21120    public byte[] getPermissionGrantBackup(int userId) {
21121        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21122            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
21123        }
21124
21125        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
21126        try {
21127            final XmlSerializer serializer = new FastXmlSerializer();
21128            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
21129            serializer.startDocument(null, true);
21130            serializer.startTag(null, TAG_PERMISSION_BACKUP);
21131
21132            synchronized (mPackages) {
21133                serializeRuntimePermissionGrantsLPr(serializer, userId);
21134            }
21135
21136            serializer.endTag(null, TAG_PERMISSION_BACKUP);
21137            serializer.endDocument();
21138            serializer.flush();
21139        } catch (Exception e) {
21140            if (DEBUG_BACKUP) {
21141                Slog.e(TAG, "Unable to write default apps for backup", e);
21142            }
21143            return null;
21144        }
21145
21146        return dataStream.toByteArray();
21147    }
21148
21149    @Override
21150    public void restorePermissionGrants(byte[] backup, int userId) {
21151        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
21152            throw new SecurityException("Only the system may call restorePermissionGrants()");
21153        }
21154
21155        try {
21156            final XmlPullParser parser = Xml.newPullParser();
21157            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
21158            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
21159                    new BlobXmlRestorer() {
21160                        @Override
21161                        public void apply(XmlPullParser parser, int userId)
21162                                throws XmlPullParserException, IOException {
21163                            synchronized (mPackages) {
21164                                processRestoredPermissionGrantsLPr(parser, userId);
21165                            }
21166                        }
21167                    } );
21168        } catch (Exception e) {
21169            if (DEBUG_BACKUP) {
21170                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
21171            }
21172        }
21173    }
21174
21175    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
21176            throws IOException {
21177        serializer.startTag(null, TAG_ALL_GRANTS);
21178
21179        final int N = mSettings.mPackages.size();
21180        for (int i = 0; i < N; i++) {
21181            final PackageSetting ps = mSettings.mPackages.valueAt(i);
21182            boolean pkgGrantsKnown = false;
21183
21184            PermissionsState packagePerms = ps.getPermissionsState();
21185
21186            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
21187                final int grantFlags = state.getFlags();
21188                // only look at grants that are not system/policy fixed
21189                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
21190                    final boolean isGranted = state.isGranted();
21191                    // And only back up the user-twiddled state bits
21192                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
21193                        final String packageName = mSettings.mPackages.keyAt(i);
21194                        if (!pkgGrantsKnown) {
21195                            serializer.startTag(null, TAG_GRANT);
21196                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
21197                            pkgGrantsKnown = true;
21198                        }
21199
21200                        final boolean userSet =
21201                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
21202                        final boolean userFixed =
21203                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
21204                        final boolean revoke =
21205                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
21206
21207                        serializer.startTag(null, TAG_PERMISSION);
21208                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
21209                        if (isGranted) {
21210                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
21211                        }
21212                        if (userSet) {
21213                            serializer.attribute(null, ATTR_USER_SET, "true");
21214                        }
21215                        if (userFixed) {
21216                            serializer.attribute(null, ATTR_USER_FIXED, "true");
21217                        }
21218                        if (revoke) {
21219                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
21220                        }
21221                        serializer.endTag(null, TAG_PERMISSION);
21222                    }
21223                }
21224            }
21225
21226            if (pkgGrantsKnown) {
21227                serializer.endTag(null, TAG_GRANT);
21228            }
21229        }
21230
21231        serializer.endTag(null, TAG_ALL_GRANTS);
21232    }
21233
21234    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
21235            throws XmlPullParserException, IOException {
21236        String pkgName = null;
21237        int outerDepth = parser.getDepth();
21238        int type;
21239        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
21240                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
21241            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
21242                continue;
21243            }
21244
21245            final String tagName = parser.getName();
21246            if (tagName.equals(TAG_GRANT)) {
21247                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
21248                if (DEBUG_BACKUP) {
21249                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
21250                }
21251            } else if (tagName.equals(TAG_PERMISSION)) {
21252
21253                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
21254                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
21255
21256                int newFlagSet = 0;
21257                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
21258                    newFlagSet |= FLAG_PERMISSION_USER_SET;
21259                }
21260                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
21261                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
21262                }
21263                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
21264                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
21265                }
21266                if (DEBUG_BACKUP) {
21267                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
21268                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
21269                }
21270                final PackageSetting ps = mSettings.mPackages.get(pkgName);
21271                if (ps != null) {
21272                    // Already installed so we apply the grant immediately
21273                    if (DEBUG_BACKUP) {
21274                        Slog.v(TAG, "        + already installed; applying");
21275                    }
21276                    PermissionsState perms = ps.getPermissionsState();
21277                    BasePermission bp = mSettings.mPermissions.get(permName);
21278                    if (bp != null) {
21279                        if (isGranted) {
21280                            perms.grantRuntimePermission(bp, userId);
21281                        }
21282                        if (newFlagSet != 0) {
21283                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
21284                        }
21285                    }
21286                } else {
21287                    // Need to wait for post-restore install to apply the grant
21288                    if (DEBUG_BACKUP) {
21289                        Slog.v(TAG, "        - not yet installed; saving for later");
21290                    }
21291                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
21292                            isGranted, newFlagSet, userId);
21293                }
21294            } else {
21295                PackageManagerService.reportSettingsProblem(Log.WARN,
21296                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
21297                XmlUtils.skipCurrentTag(parser);
21298            }
21299        }
21300
21301        scheduleWriteSettingsLocked();
21302        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
21303    }
21304
21305    @Override
21306    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
21307            int sourceUserId, int targetUserId, int flags) {
21308        mContext.enforceCallingOrSelfPermission(
21309                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21310        int callingUid = Binder.getCallingUid();
21311        enforceOwnerRights(ownerPackage, callingUid);
21312        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21313        if (intentFilter.countActions() == 0) {
21314            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
21315            return;
21316        }
21317        synchronized (mPackages) {
21318            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
21319                    ownerPackage, targetUserId, flags);
21320            CrossProfileIntentResolver resolver =
21321                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21322            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
21323            // We have all those whose filter is equal. Now checking if the rest is equal as well.
21324            if (existing != null) {
21325                int size = existing.size();
21326                for (int i = 0; i < size; i++) {
21327                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
21328                        return;
21329                    }
21330                }
21331            }
21332            resolver.addFilter(newFilter);
21333            scheduleWritePackageRestrictionsLocked(sourceUserId);
21334        }
21335    }
21336
21337    @Override
21338    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
21339        mContext.enforceCallingOrSelfPermission(
21340                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
21341        final int callingUid = Binder.getCallingUid();
21342        enforceOwnerRights(ownerPackage, callingUid);
21343        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
21344        synchronized (mPackages) {
21345            CrossProfileIntentResolver resolver =
21346                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
21347            ArraySet<CrossProfileIntentFilter> set =
21348                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
21349            for (CrossProfileIntentFilter filter : set) {
21350                if (filter.getOwnerPackage().equals(ownerPackage)) {
21351                    resolver.removeFilter(filter);
21352                }
21353            }
21354            scheduleWritePackageRestrictionsLocked(sourceUserId);
21355        }
21356    }
21357
21358    // Enforcing that callingUid is owning pkg on userId
21359    private void enforceOwnerRights(String pkg, int callingUid) {
21360        // The system owns everything.
21361        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21362            return;
21363        }
21364        final int callingUserId = UserHandle.getUserId(callingUid);
21365        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21366        if (pi == null) {
21367            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21368                    + callingUserId);
21369        }
21370        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21371            throw new SecurityException("Calling uid " + callingUid
21372                    + " does not own package " + pkg);
21373        }
21374    }
21375
21376    @Override
21377    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21378        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21379            return null;
21380        }
21381        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21382    }
21383
21384    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21385        UserManagerService ums = UserManagerService.getInstance();
21386        if (ums != null) {
21387            final UserInfo parent = ums.getProfileParent(userId);
21388            final int launcherUid = (parent != null) ? parent.id : userId;
21389            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21390            if (launcherComponent != null) {
21391                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21392                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21393                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21394                        .setPackage(launcherComponent.getPackageName());
21395                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21396            }
21397        }
21398    }
21399
21400    /**
21401     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21402     * then reports the most likely home activity or null if there are more than one.
21403     */
21404    private ComponentName getDefaultHomeActivity(int userId) {
21405        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21406        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21407        if (cn != null) {
21408            return cn;
21409        }
21410
21411        // Find the launcher with the highest priority and return that component if there are no
21412        // other home activity with the same priority.
21413        int lastPriority = Integer.MIN_VALUE;
21414        ComponentName lastComponent = null;
21415        final int size = allHomeCandidates.size();
21416        for (int i = 0; i < size; i++) {
21417            final ResolveInfo ri = allHomeCandidates.get(i);
21418            if (ri.priority > lastPriority) {
21419                lastComponent = ri.activityInfo.getComponentName();
21420                lastPriority = ri.priority;
21421            } else if (ri.priority == lastPriority) {
21422                // Two components found with same priority.
21423                lastComponent = null;
21424            }
21425        }
21426        return lastComponent;
21427    }
21428
21429    private Intent getHomeIntent() {
21430        Intent intent = new Intent(Intent.ACTION_MAIN);
21431        intent.addCategory(Intent.CATEGORY_HOME);
21432        intent.addCategory(Intent.CATEGORY_DEFAULT);
21433        return intent;
21434    }
21435
21436    private IntentFilter getHomeFilter() {
21437        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21438        filter.addCategory(Intent.CATEGORY_HOME);
21439        filter.addCategory(Intent.CATEGORY_DEFAULT);
21440        return filter;
21441    }
21442
21443    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21444            int userId) {
21445        Intent intent  = getHomeIntent();
21446        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21447                PackageManager.GET_META_DATA, userId);
21448        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21449                true, false, false, userId);
21450
21451        allHomeCandidates.clear();
21452        if (list != null) {
21453            for (ResolveInfo ri : list) {
21454                allHomeCandidates.add(ri);
21455            }
21456        }
21457        return (preferred == null || preferred.activityInfo == null)
21458                ? null
21459                : new ComponentName(preferred.activityInfo.packageName,
21460                        preferred.activityInfo.name);
21461    }
21462
21463    @Override
21464    public void setHomeActivity(ComponentName comp, int userId) {
21465        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21466            return;
21467        }
21468        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21469        getHomeActivitiesAsUser(homeActivities, userId);
21470
21471        boolean found = false;
21472
21473        final int size = homeActivities.size();
21474        final ComponentName[] set = new ComponentName[size];
21475        for (int i = 0; i < size; i++) {
21476            final ResolveInfo candidate = homeActivities.get(i);
21477            final ActivityInfo info = candidate.activityInfo;
21478            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21479            set[i] = activityName;
21480            if (!found && activityName.equals(comp)) {
21481                found = true;
21482            }
21483        }
21484        if (!found) {
21485            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21486                    + userId);
21487        }
21488        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21489                set, comp, userId);
21490    }
21491
21492    private @Nullable String getSetupWizardPackageName() {
21493        final Intent intent = new Intent(Intent.ACTION_MAIN);
21494        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21495
21496        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21497                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21498                        | MATCH_DISABLED_COMPONENTS,
21499                UserHandle.myUserId());
21500        if (matches.size() == 1) {
21501            return matches.get(0).getComponentInfo().packageName;
21502        } else {
21503            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21504                    + ": matches=" + matches);
21505            return null;
21506        }
21507    }
21508
21509    private @Nullable String getStorageManagerPackageName() {
21510        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21511
21512        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21513                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21514                        | MATCH_DISABLED_COMPONENTS,
21515                UserHandle.myUserId());
21516        if (matches.size() == 1) {
21517            return matches.get(0).getComponentInfo().packageName;
21518        } else {
21519            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21520                    + matches.size() + ": matches=" + matches);
21521            return null;
21522        }
21523    }
21524
21525    @Override
21526    public void setApplicationEnabledSetting(String appPackageName,
21527            int newState, int flags, int userId, String callingPackage) {
21528        if (!sUserManager.exists(userId)) return;
21529        if (callingPackage == null) {
21530            callingPackage = Integer.toString(Binder.getCallingUid());
21531        }
21532        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21533    }
21534
21535    @Override
21536    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21537        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21538        synchronized (mPackages) {
21539            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21540            if (pkgSetting != null) {
21541                pkgSetting.setUpdateAvailable(updateAvailable);
21542            }
21543        }
21544    }
21545
21546    @Override
21547    public void setComponentEnabledSetting(ComponentName componentName,
21548            int newState, int flags, int userId) {
21549        if (!sUserManager.exists(userId)) return;
21550        setEnabledSetting(componentName.getPackageName(),
21551                componentName.getClassName(), newState, flags, userId, null);
21552    }
21553
21554    private void setEnabledSetting(final String packageName, String className, int newState,
21555            final int flags, int userId, String callingPackage) {
21556        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21557              || newState == COMPONENT_ENABLED_STATE_ENABLED
21558              || newState == COMPONENT_ENABLED_STATE_DISABLED
21559              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21560              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21561            throw new IllegalArgumentException("Invalid new component state: "
21562                    + newState);
21563        }
21564        PackageSetting pkgSetting;
21565        final int callingUid = Binder.getCallingUid();
21566        final int permission;
21567        if (callingUid == Process.SYSTEM_UID) {
21568            permission = PackageManager.PERMISSION_GRANTED;
21569        } else {
21570            permission = mContext.checkCallingOrSelfPermission(
21571                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21572        }
21573        enforceCrossUserPermission(callingUid, userId,
21574                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21575        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21576        boolean sendNow = false;
21577        boolean isApp = (className == null);
21578        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21579        String componentName = isApp ? packageName : className;
21580        int packageUid = -1;
21581        ArrayList<String> components;
21582
21583        // reader
21584        synchronized (mPackages) {
21585            pkgSetting = mSettings.mPackages.get(packageName);
21586            if (pkgSetting == null) {
21587                if (!isCallerInstantApp) {
21588                    if (className == null) {
21589                        throw new IllegalArgumentException("Unknown package: " + packageName);
21590                    }
21591                    throw new IllegalArgumentException(
21592                            "Unknown component: " + packageName + "/" + className);
21593                } else {
21594                    // throw SecurityException to prevent leaking package information
21595                    throw new SecurityException(
21596                            "Attempt to change component state; "
21597                            + "pid=" + Binder.getCallingPid()
21598                            + ", uid=" + callingUid
21599                            + (className == null
21600                                    ? ", package=" + packageName
21601                                    : ", component=" + packageName + "/" + className));
21602                }
21603            }
21604        }
21605
21606        // Limit who can change which apps
21607        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21608            // Don't allow apps that don't have permission to modify other apps
21609            if (!allowedByPermission
21610                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21611                throw new SecurityException(
21612                        "Attempt to change component state; "
21613                        + "pid=" + Binder.getCallingPid()
21614                        + ", uid=" + callingUid
21615                        + (className == null
21616                                ? ", package=" + packageName
21617                                : ", component=" + packageName + "/" + className));
21618            }
21619            // Don't allow changing protected packages.
21620            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21621                throw new SecurityException("Cannot disable a protected package: " + packageName);
21622            }
21623        }
21624
21625        synchronized (mPackages) {
21626            if (callingUid == Process.SHELL_UID
21627                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21628                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21629                // unless it is a test package.
21630                int oldState = pkgSetting.getEnabled(userId);
21631                if (className == null
21632                    &&
21633                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21634                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21635                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21636                    &&
21637                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21638                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
21639                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21640                    // ok
21641                } else {
21642                    throw new SecurityException(
21643                            "Shell cannot change component state for " + packageName + "/"
21644                            + className + " to " + newState);
21645                }
21646            }
21647            if (className == null) {
21648                // We're dealing with an application/package level state change
21649                if (pkgSetting.getEnabled(userId) == newState) {
21650                    // Nothing to do
21651                    return;
21652                }
21653                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21654                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21655                    // Don't care about who enables an app.
21656                    callingPackage = null;
21657                }
21658                pkgSetting.setEnabled(newState, userId, callingPackage);
21659                // pkgSetting.pkg.mSetEnabled = newState;
21660            } else {
21661                // We're dealing with a component level state change
21662                // First, verify that this is a valid class name.
21663                PackageParser.Package pkg = pkgSetting.pkg;
21664                if (pkg == null || !pkg.hasComponentClassName(className)) {
21665                    if (pkg != null &&
21666                            pkg.applicationInfo.targetSdkVersion >=
21667                                    Build.VERSION_CODES.JELLY_BEAN) {
21668                        throw new IllegalArgumentException("Component class " + className
21669                                + " does not exist in " + packageName);
21670                    } else {
21671                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21672                                + className + " does not exist in " + packageName);
21673                    }
21674                }
21675                switch (newState) {
21676                case COMPONENT_ENABLED_STATE_ENABLED:
21677                    if (!pkgSetting.enableComponentLPw(className, userId)) {
21678                        return;
21679                    }
21680                    break;
21681                case COMPONENT_ENABLED_STATE_DISABLED:
21682                    if (!pkgSetting.disableComponentLPw(className, userId)) {
21683                        return;
21684                    }
21685                    break;
21686                case COMPONENT_ENABLED_STATE_DEFAULT:
21687                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
21688                        return;
21689                    }
21690                    break;
21691                default:
21692                    Slog.e(TAG, "Invalid new component state: " + newState);
21693                    return;
21694                }
21695            }
21696            scheduleWritePackageRestrictionsLocked(userId);
21697            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21698            final long callingId = Binder.clearCallingIdentity();
21699            try {
21700                updateInstantAppInstallerLocked(packageName);
21701            } finally {
21702                Binder.restoreCallingIdentity(callingId);
21703            }
21704            components = mPendingBroadcasts.get(userId, packageName);
21705            final boolean newPackage = components == null;
21706            if (newPackage) {
21707                components = new ArrayList<String>();
21708            }
21709            if (!components.contains(componentName)) {
21710                components.add(componentName);
21711            }
21712            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21713                sendNow = true;
21714                // Purge entry from pending broadcast list if another one exists already
21715                // since we are sending one right away.
21716                mPendingBroadcasts.remove(userId, packageName);
21717            } else {
21718                if (newPackage) {
21719                    mPendingBroadcasts.put(userId, packageName, components);
21720                }
21721                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21722                    // Schedule a message
21723                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21724                }
21725            }
21726        }
21727
21728        long callingId = Binder.clearCallingIdentity();
21729        try {
21730            if (sendNow) {
21731                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21732                sendPackageChangedBroadcast(packageName,
21733                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21734            }
21735        } finally {
21736            Binder.restoreCallingIdentity(callingId);
21737        }
21738    }
21739
21740    @Override
21741    public void flushPackageRestrictionsAsUser(int userId) {
21742        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21743            return;
21744        }
21745        if (!sUserManager.exists(userId)) {
21746            return;
21747        }
21748        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21749                false /* checkShell */, "flushPackageRestrictions");
21750        synchronized (mPackages) {
21751            mSettings.writePackageRestrictionsLPr(userId);
21752            mDirtyUsers.remove(userId);
21753            if (mDirtyUsers.isEmpty()) {
21754                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21755            }
21756        }
21757    }
21758
21759    private void sendPackageChangedBroadcast(String packageName,
21760            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21761        if (DEBUG_INSTALL)
21762            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21763                    + componentNames);
21764        Bundle extras = new Bundle(4);
21765        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21766        String nameList[] = new String[componentNames.size()];
21767        componentNames.toArray(nameList);
21768        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21769        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21770        extras.putInt(Intent.EXTRA_UID, packageUid);
21771        // If this is not reporting a change of the overall package, then only send it
21772        // to registered receivers.  We don't want to launch a swath of apps for every
21773        // little component state change.
21774        final int flags = !componentNames.contains(packageName)
21775                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21776        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21777                new int[] {UserHandle.getUserId(packageUid)});
21778    }
21779
21780    @Override
21781    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21782        if (!sUserManager.exists(userId)) return;
21783        final int callingUid = Binder.getCallingUid();
21784        if (getInstantAppPackageName(callingUid) != null) {
21785            return;
21786        }
21787        final int permission = mContext.checkCallingOrSelfPermission(
21788                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21789        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21790        enforceCrossUserPermission(callingUid, userId,
21791                true /* requireFullPermission */, true /* checkShell */, "stop package");
21792        // writer
21793        synchronized (mPackages) {
21794            final PackageSetting ps = mSettings.mPackages.get(packageName);
21795            if (!filterAppAccessLPr(ps, callingUid, userId)
21796                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21797                            allowedByPermission, callingUid, userId)) {
21798                scheduleWritePackageRestrictionsLocked(userId);
21799            }
21800        }
21801    }
21802
21803    @Override
21804    public String getInstallerPackageName(String packageName) {
21805        final int callingUid = Binder.getCallingUid();
21806        if (getInstantAppPackageName(callingUid) != null) {
21807            return null;
21808        }
21809        // reader
21810        synchronized (mPackages) {
21811            final PackageSetting ps = mSettings.mPackages.get(packageName);
21812            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21813                return null;
21814            }
21815            return mSettings.getInstallerPackageNameLPr(packageName);
21816        }
21817    }
21818
21819    public boolean isOrphaned(String packageName) {
21820        // reader
21821        synchronized (mPackages) {
21822            return mSettings.isOrphaned(packageName);
21823        }
21824    }
21825
21826    @Override
21827    public int getApplicationEnabledSetting(String packageName, int userId) {
21828        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21829        int callingUid = Binder.getCallingUid();
21830        enforceCrossUserPermission(callingUid, userId,
21831                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21832        // reader
21833        synchronized (mPackages) {
21834            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21835                return COMPONENT_ENABLED_STATE_DISABLED;
21836            }
21837            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21838        }
21839    }
21840
21841    @Override
21842    public int getComponentEnabledSetting(ComponentName component, int userId) {
21843        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21844        int callingUid = Binder.getCallingUid();
21845        enforceCrossUserPermission(callingUid, userId,
21846                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21847        synchronized (mPackages) {
21848            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21849                    component, TYPE_UNKNOWN, userId)) {
21850                return COMPONENT_ENABLED_STATE_DISABLED;
21851            }
21852            return mSettings.getComponentEnabledSettingLPr(component, userId);
21853        }
21854    }
21855
21856    @Override
21857    public void enterSafeMode() {
21858        enforceSystemOrRoot("Only the system can request entering safe mode");
21859
21860        if (!mSystemReady) {
21861            mSafeMode = true;
21862        }
21863    }
21864
21865    @Override
21866    public void systemReady() {
21867        enforceSystemOrRoot("Only the system can claim the system is ready");
21868
21869        mSystemReady = true;
21870        final ContentResolver resolver = mContext.getContentResolver();
21871        ContentObserver co = new ContentObserver(mHandler) {
21872            @Override
21873            public void onChange(boolean selfChange) {
21874                mEphemeralAppsDisabled =
21875                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21876                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21877            }
21878        };
21879        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21880                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21881                false, co, UserHandle.USER_SYSTEM);
21882        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21883                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21884        co.onChange(true);
21885
21886        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21887        // disabled after already being started.
21888        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21889                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21890
21891        // Read the compatibilty setting when the system is ready.
21892        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21893                mContext.getContentResolver(),
21894                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21895        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21896        if (DEBUG_SETTINGS) {
21897            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21898        }
21899
21900        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21901
21902        synchronized (mPackages) {
21903            // Verify that all of the preferred activity components actually
21904            // exist.  It is possible for applications to be updated and at
21905            // that point remove a previously declared activity component that
21906            // had been set as a preferred activity.  We try to clean this up
21907            // the next time we encounter that preferred activity, but it is
21908            // possible for the user flow to never be able to return to that
21909            // situation so here we do a sanity check to make sure we haven't
21910            // left any junk around.
21911            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21912            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21913                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21914                removed.clear();
21915                for (PreferredActivity pa : pir.filterSet()) {
21916                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21917                        removed.add(pa);
21918                    }
21919                }
21920                if (removed.size() > 0) {
21921                    for (int r=0; r<removed.size(); r++) {
21922                        PreferredActivity pa = removed.get(r);
21923                        Slog.w(TAG, "Removing dangling preferred activity: "
21924                                + pa.mPref.mComponent);
21925                        pir.removeFilter(pa);
21926                    }
21927                    mSettings.writePackageRestrictionsLPr(
21928                            mSettings.mPreferredActivities.keyAt(i));
21929                }
21930            }
21931
21932            for (int userId : UserManagerService.getInstance().getUserIds()) {
21933                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21934                    grantPermissionsUserIds = ArrayUtils.appendInt(
21935                            grantPermissionsUserIds, userId);
21936                }
21937            }
21938        }
21939        sUserManager.systemReady();
21940
21941        // If we upgraded grant all default permissions before kicking off.
21942        for (int userId : grantPermissionsUserIds) {
21943            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21944        }
21945
21946        // If we did not grant default permissions, we preload from this the
21947        // default permission exceptions lazily to ensure we don't hit the
21948        // disk on a new user creation.
21949        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21950            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21951        }
21952
21953        // Kick off any messages waiting for system ready
21954        if (mPostSystemReadyMessages != null) {
21955            for (Message msg : mPostSystemReadyMessages) {
21956                msg.sendToTarget();
21957            }
21958            mPostSystemReadyMessages = null;
21959        }
21960
21961        // Watch for external volumes that come and go over time
21962        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21963        storage.registerListener(mStorageListener);
21964
21965        mInstallerService.systemReady();
21966        mPackageDexOptimizer.systemReady();
21967
21968        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21969                StorageManagerInternal.class);
21970        StorageManagerInternal.addExternalStoragePolicy(
21971                new StorageManagerInternal.ExternalStorageMountPolicy() {
21972            @Override
21973            public int getMountMode(int uid, String packageName) {
21974                if (Process.isIsolated(uid)) {
21975                    return Zygote.MOUNT_EXTERNAL_NONE;
21976                }
21977                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21978                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21979                }
21980                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21981                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21982                }
21983                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21984                    return Zygote.MOUNT_EXTERNAL_READ;
21985                }
21986                return Zygote.MOUNT_EXTERNAL_WRITE;
21987            }
21988
21989            @Override
21990            public boolean hasExternalStorage(int uid, String packageName) {
21991                return true;
21992            }
21993        });
21994
21995        // Now that we're mostly running, clean up stale users and apps
21996        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21997        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21998
21999        if (mPrivappPermissionsViolations != null) {
22000            Slog.wtf(TAG,"Signature|privileged permissions not in "
22001                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
22002            mPrivappPermissionsViolations = null;
22003        }
22004    }
22005
22006    public void waitForAppDataPrepared() {
22007        if (mPrepareAppDataFuture == null) {
22008            return;
22009        }
22010        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
22011        mPrepareAppDataFuture = null;
22012    }
22013
22014    @Override
22015    public boolean isSafeMode() {
22016        // allow instant applications
22017        return mSafeMode;
22018    }
22019
22020    @Override
22021    public boolean hasSystemUidErrors() {
22022        // allow instant applications
22023        return mHasSystemUidErrors;
22024    }
22025
22026    static String arrayToString(int[] array) {
22027        StringBuffer buf = new StringBuffer(128);
22028        buf.append('[');
22029        if (array != null) {
22030            for (int i=0; i<array.length; i++) {
22031                if (i > 0) buf.append(", ");
22032                buf.append(array[i]);
22033            }
22034        }
22035        buf.append(']');
22036        return buf.toString();
22037    }
22038
22039    static class DumpState {
22040        public static final int DUMP_LIBS = 1 << 0;
22041        public static final int DUMP_FEATURES = 1 << 1;
22042        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
22043        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
22044        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
22045        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
22046        public static final int DUMP_PERMISSIONS = 1 << 6;
22047        public static final int DUMP_PACKAGES = 1 << 7;
22048        public static final int DUMP_SHARED_USERS = 1 << 8;
22049        public static final int DUMP_MESSAGES = 1 << 9;
22050        public static final int DUMP_PROVIDERS = 1 << 10;
22051        public static final int DUMP_VERIFIERS = 1 << 11;
22052        public static final int DUMP_PREFERRED = 1 << 12;
22053        public static final int DUMP_PREFERRED_XML = 1 << 13;
22054        public static final int DUMP_KEYSETS = 1 << 14;
22055        public static final int DUMP_VERSION = 1 << 15;
22056        public static final int DUMP_INSTALLS = 1 << 16;
22057        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
22058        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
22059        public static final int DUMP_FROZEN = 1 << 19;
22060        public static final int DUMP_DEXOPT = 1 << 20;
22061        public static final int DUMP_COMPILER_STATS = 1 << 21;
22062        public static final int DUMP_CHANGES = 1 << 22;
22063        public static final int DUMP_VOLUMES = 1 << 23;
22064
22065        public static final int OPTION_SHOW_FILTERS = 1 << 0;
22066
22067        private int mTypes;
22068
22069        private int mOptions;
22070
22071        private boolean mTitlePrinted;
22072
22073        private SharedUserSetting mSharedUser;
22074
22075        public boolean isDumping(int type) {
22076            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
22077                return true;
22078            }
22079
22080            return (mTypes & type) != 0;
22081        }
22082
22083        public void setDump(int type) {
22084            mTypes |= type;
22085        }
22086
22087        public boolean isOptionEnabled(int option) {
22088            return (mOptions & option) != 0;
22089        }
22090
22091        public void setOptionEnabled(int option) {
22092            mOptions |= option;
22093        }
22094
22095        public boolean onTitlePrinted() {
22096            final boolean printed = mTitlePrinted;
22097            mTitlePrinted = true;
22098            return printed;
22099        }
22100
22101        public boolean getTitlePrinted() {
22102            return mTitlePrinted;
22103        }
22104
22105        public void setTitlePrinted(boolean enabled) {
22106            mTitlePrinted = enabled;
22107        }
22108
22109        public SharedUserSetting getSharedUser() {
22110            return mSharedUser;
22111        }
22112
22113        public void setSharedUser(SharedUserSetting user) {
22114            mSharedUser = user;
22115        }
22116    }
22117
22118    @Override
22119    public void onShellCommand(FileDescriptor in, FileDescriptor out,
22120            FileDescriptor err, String[] args, ShellCallback callback,
22121            ResultReceiver resultReceiver) {
22122        (new PackageManagerShellCommand(this)).exec(
22123                this, in, out, err, args, callback, resultReceiver);
22124    }
22125
22126    @Override
22127    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
22128        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
22129
22130        DumpState dumpState = new DumpState();
22131        boolean fullPreferred = false;
22132        boolean checkin = false;
22133
22134        String packageName = null;
22135        ArraySet<String> permissionNames = null;
22136
22137        int opti = 0;
22138        while (opti < args.length) {
22139            String opt = args[opti];
22140            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
22141                break;
22142            }
22143            opti++;
22144
22145            if ("-a".equals(opt)) {
22146                // Right now we only know how to print all.
22147            } else if ("-h".equals(opt)) {
22148                pw.println("Package manager dump options:");
22149                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
22150                pw.println("    --checkin: dump for a checkin");
22151                pw.println("    -f: print details of intent filters");
22152                pw.println("    -h: print this help");
22153                pw.println("  cmd may be one of:");
22154                pw.println("    l[ibraries]: list known shared libraries");
22155                pw.println("    f[eatures]: list device features");
22156                pw.println("    k[eysets]: print known keysets");
22157                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
22158                pw.println("    perm[issions]: dump permissions");
22159                pw.println("    permission [name ...]: dump declaration and use of given permission");
22160                pw.println("    pref[erred]: print preferred package settings");
22161                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
22162                pw.println("    prov[iders]: dump content providers");
22163                pw.println("    p[ackages]: dump installed packages");
22164                pw.println("    s[hared-users]: dump shared user IDs");
22165                pw.println("    m[essages]: print collected runtime messages");
22166                pw.println("    v[erifiers]: print package verifier info");
22167                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
22168                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
22169                pw.println("    version: print database version info");
22170                pw.println("    write: write current settings now");
22171                pw.println("    installs: details about install sessions");
22172                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
22173                pw.println("    dexopt: dump dexopt state");
22174                pw.println("    compiler-stats: dump compiler statistics");
22175                pw.println("    enabled-overlays: dump list of enabled overlay packages");
22176                pw.println("    <package.name>: info about given package");
22177                return;
22178            } else if ("--checkin".equals(opt)) {
22179                checkin = true;
22180            } else if ("-f".equals(opt)) {
22181                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22182            } else if ("--proto".equals(opt)) {
22183                dumpProto(fd);
22184                return;
22185            } else {
22186                pw.println("Unknown argument: " + opt + "; use -h for help");
22187            }
22188        }
22189
22190        // Is the caller requesting to dump a particular piece of data?
22191        if (opti < args.length) {
22192            String cmd = args[opti];
22193            opti++;
22194            // Is this a package name?
22195            if ("android".equals(cmd) || cmd.contains(".")) {
22196                packageName = cmd;
22197                // When dumping a single package, we always dump all of its
22198                // filter information since the amount of data will be reasonable.
22199                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
22200            } else if ("check-permission".equals(cmd)) {
22201                if (opti >= args.length) {
22202                    pw.println("Error: check-permission missing permission argument");
22203                    return;
22204                }
22205                String perm = args[opti];
22206                opti++;
22207                if (opti >= args.length) {
22208                    pw.println("Error: check-permission missing package argument");
22209                    return;
22210                }
22211
22212                String pkg = args[opti];
22213                opti++;
22214                int user = UserHandle.getUserId(Binder.getCallingUid());
22215                if (opti < args.length) {
22216                    try {
22217                        user = Integer.parseInt(args[opti]);
22218                    } catch (NumberFormatException e) {
22219                        pw.println("Error: check-permission user argument is not a number: "
22220                                + args[opti]);
22221                        return;
22222                    }
22223                }
22224
22225                // Normalize package name to handle renamed packages and static libs
22226                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
22227
22228                pw.println(checkPermission(perm, pkg, user));
22229                return;
22230            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
22231                dumpState.setDump(DumpState.DUMP_LIBS);
22232            } else if ("f".equals(cmd) || "features".equals(cmd)) {
22233                dumpState.setDump(DumpState.DUMP_FEATURES);
22234            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
22235                if (opti >= args.length) {
22236                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
22237                            | DumpState.DUMP_SERVICE_RESOLVERS
22238                            | DumpState.DUMP_RECEIVER_RESOLVERS
22239                            | DumpState.DUMP_CONTENT_RESOLVERS);
22240                } else {
22241                    while (opti < args.length) {
22242                        String name = args[opti];
22243                        if ("a".equals(name) || "activity".equals(name)) {
22244                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
22245                        } else if ("s".equals(name) || "service".equals(name)) {
22246                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
22247                        } else if ("r".equals(name) || "receiver".equals(name)) {
22248                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
22249                        } else if ("c".equals(name) || "content".equals(name)) {
22250                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
22251                        } else {
22252                            pw.println("Error: unknown resolver table type: " + name);
22253                            return;
22254                        }
22255                        opti++;
22256                    }
22257                }
22258            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
22259                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
22260            } else if ("permission".equals(cmd)) {
22261                if (opti >= args.length) {
22262                    pw.println("Error: permission requires permission name");
22263                    return;
22264                }
22265                permissionNames = new ArraySet<>();
22266                while (opti < args.length) {
22267                    permissionNames.add(args[opti]);
22268                    opti++;
22269                }
22270                dumpState.setDump(DumpState.DUMP_PERMISSIONS
22271                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
22272            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
22273                dumpState.setDump(DumpState.DUMP_PREFERRED);
22274            } else if ("preferred-xml".equals(cmd)) {
22275                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
22276                if (opti < args.length && "--full".equals(args[opti])) {
22277                    fullPreferred = true;
22278                    opti++;
22279                }
22280            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
22281                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
22282            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
22283                dumpState.setDump(DumpState.DUMP_PACKAGES);
22284            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
22285                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
22286            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
22287                dumpState.setDump(DumpState.DUMP_PROVIDERS);
22288            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
22289                dumpState.setDump(DumpState.DUMP_MESSAGES);
22290            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
22291                dumpState.setDump(DumpState.DUMP_VERIFIERS);
22292            } else if ("i".equals(cmd) || "ifv".equals(cmd)
22293                    || "intent-filter-verifiers".equals(cmd)) {
22294                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
22295            } else if ("version".equals(cmd)) {
22296                dumpState.setDump(DumpState.DUMP_VERSION);
22297            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
22298                dumpState.setDump(DumpState.DUMP_KEYSETS);
22299            } else if ("installs".equals(cmd)) {
22300                dumpState.setDump(DumpState.DUMP_INSTALLS);
22301            } else if ("frozen".equals(cmd)) {
22302                dumpState.setDump(DumpState.DUMP_FROZEN);
22303            } else if ("volumes".equals(cmd)) {
22304                dumpState.setDump(DumpState.DUMP_VOLUMES);
22305            } else if ("dexopt".equals(cmd)) {
22306                dumpState.setDump(DumpState.DUMP_DEXOPT);
22307            } else if ("compiler-stats".equals(cmd)) {
22308                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
22309            } else if ("changes".equals(cmd)) {
22310                dumpState.setDump(DumpState.DUMP_CHANGES);
22311            } else if ("write".equals(cmd)) {
22312                synchronized (mPackages) {
22313                    mSettings.writeLPr();
22314                    pw.println("Settings written.");
22315                    return;
22316                }
22317            }
22318        }
22319
22320        if (checkin) {
22321            pw.println("vers,1");
22322        }
22323
22324        // reader
22325        synchronized (mPackages) {
22326            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
22327                if (!checkin) {
22328                    if (dumpState.onTitlePrinted())
22329                        pw.println();
22330                    pw.println("Database versions:");
22331                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
22332                }
22333            }
22334
22335            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
22336                if (!checkin) {
22337                    if (dumpState.onTitlePrinted())
22338                        pw.println();
22339                    pw.println("Verifiers:");
22340                    pw.print("  Required: ");
22341                    pw.print(mRequiredVerifierPackage);
22342                    pw.print(" (uid=");
22343                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22344                            UserHandle.USER_SYSTEM));
22345                    pw.println(")");
22346                } else if (mRequiredVerifierPackage != null) {
22347                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
22348                    pw.print(",");
22349                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22350                            UserHandle.USER_SYSTEM));
22351                }
22352            }
22353
22354            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22355                    packageName == null) {
22356                if (mIntentFilterVerifierComponent != null) {
22357                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22358                    if (!checkin) {
22359                        if (dumpState.onTitlePrinted())
22360                            pw.println();
22361                        pw.println("Intent Filter Verifier:");
22362                        pw.print("  Using: ");
22363                        pw.print(verifierPackageName);
22364                        pw.print(" (uid=");
22365                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22366                                UserHandle.USER_SYSTEM));
22367                        pw.println(")");
22368                    } else if (verifierPackageName != null) {
22369                        pw.print("ifv,"); pw.print(verifierPackageName);
22370                        pw.print(",");
22371                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22372                                UserHandle.USER_SYSTEM));
22373                    }
22374                } else {
22375                    pw.println();
22376                    pw.println("No Intent Filter Verifier available!");
22377                }
22378            }
22379
22380            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22381                boolean printedHeader = false;
22382                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22383                while (it.hasNext()) {
22384                    String libName = it.next();
22385                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22386                    if (versionedLib == null) {
22387                        continue;
22388                    }
22389                    final int versionCount = versionedLib.size();
22390                    for (int i = 0; i < versionCount; i++) {
22391                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22392                        if (!checkin) {
22393                            if (!printedHeader) {
22394                                if (dumpState.onTitlePrinted())
22395                                    pw.println();
22396                                pw.println("Libraries:");
22397                                printedHeader = true;
22398                            }
22399                            pw.print("  ");
22400                        } else {
22401                            pw.print("lib,");
22402                        }
22403                        pw.print(libEntry.info.getName());
22404                        if (libEntry.info.isStatic()) {
22405                            pw.print(" version=" + libEntry.info.getVersion());
22406                        }
22407                        if (!checkin) {
22408                            pw.print(" -> ");
22409                        }
22410                        if (libEntry.path != null) {
22411                            pw.print(" (jar) ");
22412                            pw.print(libEntry.path);
22413                        } else {
22414                            pw.print(" (apk) ");
22415                            pw.print(libEntry.apk);
22416                        }
22417                        pw.println();
22418                    }
22419                }
22420            }
22421
22422            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22423                if (dumpState.onTitlePrinted())
22424                    pw.println();
22425                if (!checkin) {
22426                    pw.println("Features:");
22427                }
22428
22429                synchronized (mAvailableFeatures) {
22430                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22431                        if (checkin) {
22432                            pw.print("feat,");
22433                            pw.print(feat.name);
22434                            pw.print(",");
22435                            pw.println(feat.version);
22436                        } else {
22437                            pw.print("  ");
22438                            pw.print(feat.name);
22439                            if (feat.version > 0) {
22440                                pw.print(" version=");
22441                                pw.print(feat.version);
22442                            }
22443                            pw.println();
22444                        }
22445                    }
22446                }
22447            }
22448
22449            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22450                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22451                        : "Activity Resolver Table:", "  ", packageName,
22452                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22453                    dumpState.setTitlePrinted(true);
22454                }
22455            }
22456            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22457                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22458                        : "Receiver Resolver Table:", "  ", packageName,
22459                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22460                    dumpState.setTitlePrinted(true);
22461                }
22462            }
22463            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22464                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22465                        : "Service Resolver Table:", "  ", packageName,
22466                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22467                    dumpState.setTitlePrinted(true);
22468                }
22469            }
22470            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22471                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22472                        : "Provider Resolver Table:", "  ", packageName,
22473                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22474                    dumpState.setTitlePrinted(true);
22475                }
22476            }
22477
22478            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22479                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22480                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22481                    int user = mSettings.mPreferredActivities.keyAt(i);
22482                    if (pir.dump(pw,
22483                            dumpState.getTitlePrinted()
22484                                ? "\nPreferred Activities User " + user + ":"
22485                                : "Preferred Activities User " + user + ":", "  ",
22486                            packageName, true, false)) {
22487                        dumpState.setTitlePrinted(true);
22488                    }
22489                }
22490            }
22491
22492            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22493                pw.flush();
22494                FileOutputStream fout = new FileOutputStream(fd);
22495                BufferedOutputStream str = new BufferedOutputStream(fout);
22496                XmlSerializer serializer = new FastXmlSerializer();
22497                try {
22498                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22499                    serializer.startDocument(null, true);
22500                    serializer.setFeature(
22501                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22502                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22503                    serializer.endDocument();
22504                    serializer.flush();
22505                } catch (IllegalArgumentException e) {
22506                    pw.println("Failed writing: " + e);
22507                } catch (IllegalStateException e) {
22508                    pw.println("Failed writing: " + e);
22509                } catch (IOException e) {
22510                    pw.println("Failed writing: " + e);
22511                }
22512            }
22513
22514            if (!checkin
22515                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22516                    && packageName == null) {
22517                pw.println();
22518                int count = mSettings.mPackages.size();
22519                if (count == 0) {
22520                    pw.println("No applications!");
22521                    pw.println();
22522                } else {
22523                    final String prefix = "  ";
22524                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22525                    if (allPackageSettings.size() == 0) {
22526                        pw.println("No domain preferred apps!");
22527                        pw.println();
22528                    } else {
22529                        pw.println("App verification status:");
22530                        pw.println();
22531                        count = 0;
22532                        for (PackageSetting ps : allPackageSettings) {
22533                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22534                            if (ivi == null || ivi.getPackageName() == null) continue;
22535                            pw.println(prefix + "Package: " + ivi.getPackageName());
22536                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22537                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22538                            pw.println();
22539                            count++;
22540                        }
22541                        if (count == 0) {
22542                            pw.println(prefix + "No app verification established.");
22543                            pw.println();
22544                        }
22545                        for (int userId : sUserManager.getUserIds()) {
22546                            pw.println("App linkages for user " + userId + ":");
22547                            pw.println();
22548                            count = 0;
22549                            for (PackageSetting ps : allPackageSettings) {
22550                                final long status = ps.getDomainVerificationStatusForUser(userId);
22551                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22552                                        && !DEBUG_DOMAIN_VERIFICATION) {
22553                                    continue;
22554                                }
22555                                pw.println(prefix + "Package: " + ps.name);
22556                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22557                                String statusStr = IntentFilterVerificationInfo.
22558                                        getStatusStringFromValue(status);
22559                                pw.println(prefix + "Status:  " + statusStr);
22560                                pw.println();
22561                                count++;
22562                            }
22563                            if (count == 0) {
22564                                pw.println(prefix + "No configured app linkages.");
22565                                pw.println();
22566                            }
22567                        }
22568                    }
22569                }
22570            }
22571
22572            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22573                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22574                if (packageName == null && permissionNames == null) {
22575                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22576                        if (iperm == 0) {
22577                            if (dumpState.onTitlePrinted())
22578                                pw.println();
22579                            pw.println("AppOp Permissions:");
22580                        }
22581                        pw.print("  AppOp Permission ");
22582                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22583                        pw.println(":");
22584                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22585                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22586                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22587                        }
22588                    }
22589                }
22590            }
22591
22592            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22593                boolean printedSomething = false;
22594                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22595                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22596                        continue;
22597                    }
22598                    if (!printedSomething) {
22599                        if (dumpState.onTitlePrinted())
22600                            pw.println();
22601                        pw.println("Registered ContentProviders:");
22602                        printedSomething = true;
22603                    }
22604                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22605                    pw.print("    "); pw.println(p.toString());
22606                }
22607                printedSomething = false;
22608                for (Map.Entry<String, PackageParser.Provider> entry :
22609                        mProvidersByAuthority.entrySet()) {
22610                    PackageParser.Provider p = entry.getValue();
22611                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22612                        continue;
22613                    }
22614                    if (!printedSomething) {
22615                        if (dumpState.onTitlePrinted())
22616                            pw.println();
22617                        pw.println("ContentProvider Authorities:");
22618                        printedSomething = true;
22619                    }
22620                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22621                    pw.print("    "); pw.println(p.toString());
22622                    if (p.info != null && p.info.applicationInfo != null) {
22623                        final String appInfo = p.info.applicationInfo.toString();
22624                        pw.print("      applicationInfo="); pw.println(appInfo);
22625                    }
22626                }
22627            }
22628
22629            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22630                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22631            }
22632
22633            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22634                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22635            }
22636
22637            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22638                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22639            }
22640
22641            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22642                if (dumpState.onTitlePrinted()) pw.println();
22643                pw.println("Package Changes:");
22644                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22645                final int K = mChangedPackages.size();
22646                for (int i = 0; i < K; i++) {
22647                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22648                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22649                    final int N = changes.size();
22650                    if (N == 0) {
22651                        pw.print("    "); pw.println("No packages changed");
22652                    } else {
22653                        for (int j = 0; j < N; j++) {
22654                            final String pkgName = changes.valueAt(j);
22655                            final int sequenceNumber = changes.keyAt(j);
22656                            pw.print("    ");
22657                            pw.print("seq=");
22658                            pw.print(sequenceNumber);
22659                            pw.print(", package=");
22660                            pw.println(pkgName);
22661                        }
22662                    }
22663                }
22664            }
22665
22666            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22667                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22668            }
22669
22670            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22671                // XXX should handle packageName != null by dumping only install data that
22672                // the given package is involved with.
22673                if (dumpState.onTitlePrinted()) pw.println();
22674
22675                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22676                ipw.println();
22677                ipw.println("Frozen packages:");
22678                ipw.increaseIndent();
22679                if (mFrozenPackages.size() == 0) {
22680                    ipw.println("(none)");
22681                } else {
22682                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22683                        ipw.println(mFrozenPackages.valueAt(i));
22684                    }
22685                }
22686                ipw.decreaseIndent();
22687            }
22688
22689            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
22690                if (dumpState.onTitlePrinted()) pw.println();
22691
22692                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22693                ipw.println();
22694                ipw.println("Loaded volumes:");
22695                ipw.increaseIndent();
22696                if (mLoadedVolumes.size() == 0) {
22697                    ipw.println("(none)");
22698                } else {
22699                    for (int i = 0; i < mLoadedVolumes.size(); i++) {
22700                        ipw.println(mLoadedVolumes.valueAt(i));
22701                    }
22702                }
22703                ipw.decreaseIndent();
22704            }
22705
22706            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22707                if (dumpState.onTitlePrinted()) pw.println();
22708                dumpDexoptStateLPr(pw, packageName);
22709            }
22710
22711            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22712                if (dumpState.onTitlePrinted()) pw.println();
22713                dumpCompilerStatsLPr(pw, packageName);
22714            }
22715
22716            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22717                if (dumpState.onTitlePrinted()) pw.println();
22718                mSettings.dumpReadMessagesLPr(pw, dumpState);
22719
22720                pw.println();
22721                pw.println("Package warning messages:");
22722                BufferedReader in = null;
22723                String line = null;
22724                try {
22725                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22726                    while ((line = in.readLine()) != null) {
22727                        if (line.contains("ignored: updated version")) continue;
22728                        pw.println(line);
22729                    }
22730                } catch (IOException ignored) {
22731                } finally {
22732                    IoUtils.closeQuietly(in);
22733                }
22734            }
22735
22736            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22737                BufferedReader in = null;
22738                String line = null;
22739                try {
22740                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22741                    while ((line = in.readLine()) != null) {
22742                        if (line.contains("ignored: updated version")) continue;
22743                        pw.print("msg,");
22744                        pw.println(line);
22745                    }
22746                } catch (IOException ignored) {
22747                } finally {
22748                    IoUtils.closeQuietly(in);
22749                }
22750            }
22751        }
22752
22753        // PackageInstaller should be called outside of mPackages lock
22754        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22755            // XXX should handle packageName != null by dumping only install data that
22756            // the given package is involved with.
22757            if (dumpState.onTitlePrinted()) pw.println();
22758            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22759        }
22760    }
22761
22762    private void dumpProto(FileDescriptor fd) {
22763        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22764
22765        synchronized (mPackages) {
22766            final long requiredVerifierPackageToken =
22767                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22768            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22769            proto.write(
22770                    PackageServiceDumpProto.PackageShortProto.UID,
22771                    getPackageUid(
22772                            mRequiredVerifierPackage,
22773                            MATCH_DEBUG_TRIAGED_MISSING,
22774                            UserHandle.USER_SYSTEM));
22775            proto.end(requiredVerifierPackageToken);
22776
22777            if (mIntentFilterVerifierComponent != null) {
22778                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22779                final long verifierPackageToken =
22780                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22781                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22782                proto.write(
22783                        PackageServiceDumpProto.PackageShortProto.UID,
22784                        getPackageUid(
22785                                verifierPackageName,
22786                                MATCH_DEBUG_TRIAGED_MISSING,
22787                                UserHandle.USER_SYSTEM));
22788                proto.end(verifierPackageToken);
22789            }
22790
22791            dumpSharedLibrariesProto(proto);
22792            dumpFeaturesProto(proto);
22793            mSettings.dumpPackagesProto(proto);
22794            mSettings.dumpSharedUsersProto(proto);
22795            dumpMessagesProto(proto);
22796        }
22797        proto.flush();
22798    }
22799
22800    private void dumpMessagesProto(ProtoOutputStream proto) {
22801        BufferedReader in = null;
22802        String line = null;
22803        try {
22804            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22805            while ((line = in.readLine()) != null) {
22806                if (line.contains("ignored: updated version")) continue;
22807                proto.write(PackageServiceDumpProto.MESSAGES, line);
22808            }
22809        } catch (IOException ignored) {
22810        } finally {
22811            IoUtils.closeQuietly(in);
22812        }
22813    }
22814
22815    private void dumpFeaturesProto(ProtoOutputStream proto) {
22816        synchronized (mAvailableFeatures) {
22817            final int count = mAvailableFeatures.size();
22818            for (int i = 0; i < count; i++) {
22819                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22820                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22821                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22822                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22823                proto.end(featureToken);
22824            }
22825        }
22826    }
22827
22828    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22829        final int count = mSharedLibraries.size();
22830        for (int i = 0; i < count; i++) {
22831            final String libName = mSharedLibraries.keyAt(i);
22832            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22833            if (versionedLib == null) {
22834                continue;
22835            }
22836            final int versionCount = versionedLib.size();
22837            for (int j = 0; j < versionCount; j++) {
22838                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22839                final long sharedLibraryToken =
22840                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22841                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22842                final boolean isJar = (libEntry.path != null);
22843                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22844                if (isJar) {
22845                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22846                } else {
22847                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22848                }
22849                proto.end(sharedLibraryToken);
22850            }
22851        }
22852    }
22853
22854    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22855        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22856        ipw.println();
22857        ipw.println("Dexopt state:");
22858        ipw.increaseIndent();
22859        Collection<PackageParser.Package> packages = null;
22860        if (packageName != null) {
22861            PackageParser.Package targetPackage = mPackages.get(packageName);
22862            if (targetPackage != null) {
22863                packages = Collections.singletonList(targetPackage);
22864            } else {
22865                ipw.println("Unable to find package: " + packageName);
22866                return;
22867            }
22868        } else {
22869            packages = mPackages.values();
22870        }
22871
22872        for (PackageParser.Package pkg : packages) {
22873            ipw.println("[" + pkg.packageName + "]");
22874            ipw.increaseIndent();
22875            mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
22876                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
22877            ipw.decreaseIndent();
22878        }
22879    }
22880
22881    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22882        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22883        ipw.println();
22884        ipw.println("Compiler stats:");
22885        ipw.increaseIndent();
22886        Collection<PackageParser.Package> packages = null;
22887        if (packageName != null) {
22888            PackageParser.Package targetPackage = mPackages.get(packageName);
22889            if (targetPackage != null) {
22890                packages = Collections.singletonList(targetPackage);
22891            } else {
22892                ipw.println("Unable to find package: " + packageName);
22893                return;
22894            }
22895        } else {
22896            packages = mPackages.values();
22897        }
22898
22899        for (PackageParser.Package pkg : packages) {
22900            ipw.println("[" + pkg.packageName + "]");
22901            ipw.increaseIndent();
22902
22903            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22904            if (stats == null) {
22905                ipw.println("(No recorded stats)");
22906            } else {
22907                stats.dump(ipw);
22908            }
22909            ipw.decreaseIndent();
22910        }
22911    }
22912
22913    private String dumpDomainString(String packageName) {
22914        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22915                .getList();
22916        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22917
22918        ArraySet<String> result = new ArraySet<>();
22919        if (iviList.size() > 0) {
22920            for (IntentFilterVerificationInfo ivi : iviList) {
22921                for (String host : ivi.getDomains()) {
22922                    result.add(host);
22923                }
22924            }
22925        }
22926        if (filters != null && filters.size() > 0) {
22927            for (IntentFilter filter : filters) {
22928                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22929                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22930                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22931                    result.addAll(filter.getHostsList());
22932                }
22933            }
22934        }
22935
22936        StringBuilder sb = new StringBuilder(result.size() * 16);
22937        for (String domain : result) {
22938            if (sb.length() > 0) sb.append(" ");
22939            sb.append(domain);
22940        }
22941        return sb.toString();
22942    }
22943
22944    // ------- apps on sdcard specific code -------
22945    static final boolean DEBUG_SD_INSTALL = false;
22946
22947    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22948
22949    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22950
22951    private boolean mMediaMounted = false;
22952
22953    static String getEncryptKey() {
22954        try {
22955            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22956                    SD_ENCRYPTION_KEYSTORE_NAME);
22957            if (sdEncKey == null) {
22958                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22959                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22960                if (sdEncKey == null) {
22961                    Slog.e(TAG, "Failed to create encryption keys");
22962                    return null;
22963                }
22964            }
22965            return sdEncKey;
22966        } catch (NoSuchAlgorithmException nsae) {
22967            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22968            return null;
22969        } catch (IOException ioe) {
22970            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22971            return null;
22972        }
22973    }
22974
22975    /*
22976     * Update media status on PackageManager.
22977     */
22978    @Override
22979    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
22980        enforceSystemOrRoot("Media status can only be updated by the system");
22981        // reader; this apparently protects mMediaMounted, but should probably
22982        // be a different lock in that case.
22983        synchronized (mPackages) {
22984            Log.i(TAG, "Updating external media status from "
22985                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
22986                    + (mediaStatus ? "mounted" : "unmounted"));
22987            if (DEBUG_SD_INSTALL)
22988                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
22989                        + ", mMediaMounted=" + mMediaMounted);
22990            if (mediaStatus == mMediaMounted) {
22991                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
22992                        : 0, -1);
22993                mHandler.sendMessage(msg);
22994                return;
22995            }
22996            mMediaMounted = mediaStatus;
22997        }
22998        // Queue up an async operation since the package installation may take a
22999        // little while.
23000        mHandler.post(new Runnable() {
23001            public void run() {
23002                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
23003            }
23004        });
23005    }
23006
23007    /**
23008     * Called by StorageManagerService when the initial ASECs to scan are available.
23009     * Should block until all the ASEC containers are finished being scanned.
23010     */
23011    public void scanAvailableAsecs() {
23012        updateExternalMediaStatusInner(true, false, false);
23013    }
23014
23015    /*
23016     * Collect information of applications on external media, map them against
23017     * existing containers and update information based on current mount status.
23018     * Please note that we always have to report status if reportStatus has been
23019     * set to true especially when unloading packages.
23020     */
23021    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
23022            boolean externalStorage) {
23023        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
23024        int[] uidArr = EmptyArray.INT;
23025
23026        final String[] list = PackageHelper.getSecureContainerList();
23027        if (ArrayUtils.isEmpty(list)) {
23028            Log.i(TAG, "No secure containers found");
23029        } else {
23030            // Process list of secure containers and categorize them
23031            // as active or stale based on their package internal state.
23032
23033            // reader
23034            synchronized (mPackages) {
23035                for (String cid : list) {
23036                    // Leave stages untouched for now; installer service owns them
23037                    if (PackageInstallerService.isStageName(cid)) continue;
23038
23039                    if (DEBUG_SD_INSTALL)
23040                        Log.i(TAG, "Processing container " + cid);
23041                    String pkgName = getAsecPackageName(cid);
23042                    if (pkgName == null) {
23043                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
23044                        continue;
23045                    }
23046                    if (DEBUG_SD_INSTALL)
23047                        Log.i(TAG, "Looking for pkg : " + pkgName);
23048
23049                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
23050                    if (ps == null) {
23051                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
23052                        continue;
23053                    }
23054
23055                    /*
23056                     * Skip packages that are not external if we're unmounting
23057                     * external storage.
23058                     */
23059                    if (externalStorage && !isMounted && !isExternal(ps)) {
23060                        continue;
23061                    }
23062
23063                    final AsecInstallArgs args = new AsecInstallArgs(cid,
23064                            getAppDexInstructionSets(ps), ps.isForwardLocked());
23065                    // The package status is changed only if the code path
23066                    // matches between settings and the container id.
23067                    if (ps.codePathString != null
23068                            && ps.codePathString.startsWith(args.getCodePath())) {
23069                        if (DEBUG_SD_INSTALL) {
23070                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
23071                                    + " at code path: " + ps.codePathString);
23072                        }
23073
23074                        // We do have a valid package installed on sdcard
23075                        processCids.put(args, ps.codePathString);
23076                        final int uid = ps.appId;
23077                        if (uid != -1) {
23078                            uidArr = ArrayUtils.appendInt(uidArr, uid);
23079                        }
23080                    } else {
23081                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
23082                                + ps.codePathString);
23083                    }
23084                }
23085            }
23086
23087            Arrays.sort(uidArr);
23088        }
23089
23090        // Process packages with valid entries.
23091        if (isMounted) {
23092            if (DEBUG_SD_INSTALL)
23093                Log.i(TAG, "Loading packages");
23094            loadMediaPackages(processCids, uidArr, externalStorage);
23095            startCleaningPackages();
23096            mInstallerService.onSecureContainersAvailable();
23097        } else {
23098            if (DEBUG_SD_INSTALL)
23099                Log.i(TAG, "Unloading packages");
23100            unloadMediaPackages(processCids, uidArr, reportStatus);
23101        }
23102    }
23103
23104    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23105            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
23106        final int size = infos.size();
23107        final String[] packageNames = new String[size];
23108        final int[] packageUids = new int[size];
23109        for (int i = 0; i < size; i++) {
23110            final ApplicationInfo info = infos.get(i);
23111            packageNames[i] = info.packageName;
23112            packageUids[i] = info.uid;
23113        }
23114        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
23115                finishedReceiver);
23116    }
23117
23118    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23119            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23120        sendResourcesChangedBroadcast(mediaStatus, replacing,
23121                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
23122    }
23123
23124    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
23125            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
23126        int size = pkgList.length;
23127        if (size > 0) {
23128            // Send broadcasts here
23129            Bundle extras = new Bundle();
23130            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
23131            if (uidArr != null) {
23132                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
23133            }
23134            if (replacing) {
23135                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
23136            }
23137            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
23138                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
23139            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
23140        }
23141    }
23142
23143   /*
23144     * Look at potentially valid container ids from processCids If package
23145     * information doesn't match the one on record or package scanning fails,
23146     * the cid is added to list of removeCids. We currently don't delete stale
23147     * containers.
23148     */
23149    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
23150            boolean externalStorage) {
23151        ArrayList<String> pkgList = new ArrayList<String>();
23152        Set<AsecInstallArgs> keys = processCids.keySet();
23153
23154        for (AsecInstallArgs args : keys) {
23155            String codePath = processCids.get(args);
23156            if (DEBUG_SD_INSTALL)
23157                Log.i(TAG, "Loading container : " + args.cid);
23158            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
23159            try {
23160                // Make sure there are no container errors first.
23161                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
23162                    Slog.e(TAG, "Failed to mount cid : " + args.cid
23163                            + " when installing from sdcard");
23164                    continue;
23165                }
23166                // Check code path here.
23167                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
23168                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
23169                            + " does not match one in settings " + codePath);
23170                    continue;
23171                }
23172                // Parse package
23173                int parseFlags = mDefParseFlags;
23174                if (args.isExternalAsec()) {
23175                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
23176                }
23177                if (args.isFwdLocked()) {
23178                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
23179                }
23180
23181                synchronized (mInstallLock) {
23182                    PackageParser.Package pkg = null;
23183                    try {
23184                        // Sadly we don't know the package name yet to freeze it
23185                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
23186                                SCAN_IGNORE_FROZEN, 0, null);
23187                    } catch (PackageManagerException e) {
23188                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
23189                    }
23190                    // Scan the package
23191                    if (pkg != null) {
23192                        /*
23193                         * TODO why is the lock being held? doPostInstall is
23194                         * called in other places without the lock. This needs
23195                         * to be straightened out.
23196                         */
23197                        // writer
23198                        synchronized (mPackages) {
23199                            retCode = PackageManager.INSTALL_SUCCEEDED;
23200                            pkgList.add(pkg.packageName);
23201                            // Post process args
23202                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
23203                                    pkg.applicationInfo.uid);
23204                        }
23205                    } else {
23206                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
23207                    }
23208                }
23209
23210            } finally {
23211                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
23212                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
23213                }
23214            }
23215        }
23216        // writer
23217        synchronized (mPackages) {
23218            // If the platform SDK has changed since the last time we booted,
23219            // we need to re-grant app permission to catch any new ones that
23220            // appear. This is really a hack, and means that apps can in some
23221            // cases get permissions that the user didn't initially explicitly
23222            // allow... it would be nice to have some better way to handle
23223            // this situation.
23224            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
23225                    : mSettings.getInternalVersion();
23226            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
23227                    : StorageManager.UUID_PRIVATE_INTERNAL;
23228
23229            int updateFlags = UPDATE_PERMISSIONS_ALL;
23230            if (ver.sdkVersion != mSdkVersion) {
23231                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23232                        + mSdkVersion + "; regranting permissions for external");
23233                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23234            }
23235            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23236
23237            // Yay, everything is now upgraded
23238            ver.forceCurrent();
23239
23240            // can downgrade to reader
23241            // Persist settings
23242            mSettings.writeLPr();
23243        }
23244        // Send a broadcast to let everyone know we are done processing
23245        if (pkgList.size() > 0) {
23246            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
23247        }
23248    }
23249
23250   /*
23251     * Utility method to unload a list of specified containers
23252     */
23253    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
23254        // Just unmount all valid containers.
23255        for (AsecInstallArgs arg : cidArgs) {
23256            synchronized (mInstallLock) {
23257                arg.doPostDeleteLI(false);
23258           }
23259       }
23260   }
23261
23262    /*
23263     * Unload packages mounted on external media. This involves deleting package
23264     * data from internal structures, sending broadcasts about disabled packages,
23265     * gc'ing to free up references, unmounting all secure containers
23266     * corresponding to packages on external media, and posting a
23267     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
23268     * that we always have to post this message if status has been requested no
23269     * matter what.
23270     */
23271    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
23272            final boolean reportStatus) {
23273        if (DEBUG_SD_INSTALL)
23274            Log.i(TAG, "unloading media packages");
23275        ArrayList<String> pkgList = new ArrayList<String>();
23276        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
23277        final Set<AsecInstallArgs> keys = processCids.keySet();
23278        for (AsecInstallArgs args : keys) {
23279            String pkgName = args.getPackageName();
23280            if (DEBUG_SD_INSTALL)
23281                Log.i(TAG, "Trying to unload pkg : " + pkgName);
23282            // Delete package internally
23283            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23284            synchronized (mInstallLock) {
23285                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23286                final boolean res;
23287                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
23288                        "unloadMediaPackages")) {
23289                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
23290                            null);
23291                }
23292                if (res) {
23293                    pkgList.add(pkgName);
23294                } else {
23295                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
23296                    failedList.add(args);
23297                }
23298            }
23299        }
23300
23301        // reader
23302        synchronized (mPackages) {
23303            // We didn't update the settings after removing each package;
23304            // write them now for all packages.
23305            mSettings.writeLPr();
23306        }
23307
23308        // We have to absolutely send UPDATED_MEDIA_STATUS only
23309        // after confirming that all the receivers processed the ordered
23310        // broadcast when packages get disabled, force a gc to clean things up.
23311        // and unload all the containers.
23312        if (pkgList.size() > 0) {
23313            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
23314                    new IIntentReceiver.Stub() {
23315                public void performReceive(Intent intent, int resultCode, String data,
23316                        Bundle extras, boolean ordered, boolean sticky,
23317                        int sendingUser) throws RemoteException {
23318                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
23319                            reportStatus ? 1 : 0, 1, keys);
23320                    mHandler.sendMessage(msg);
23321                }
23322            });
23323        } else {
23324            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
23325                    keys);
23326            mHandler.sendMessage(msg);
23327        }
23328    }
23329
23330    private void loadPrivatePackages(final VolumeInfo vol) {
23331        mHandler.post(new Runnable() {
23332            @Override
23333            public void run() {
23334                loadPrivatePackagesInner(vol);
23335            }
23336        });
23337    }
23338
23339    private void loadPrivatePackagesInner(VolumeInfo vol) {
23340        final String volumeUuid = vol.fsUuid;
23341        if (TextUtils.isEmpty(volumeUuid)) {
23342            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
23343            return;
23344        }
23345
23346        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23347        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23348        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23349
23350        final VersionInfo ver;
23351        final List<PackageSetting> packages;
23352        synchronized (mPackages) {
23353            ver = mSettings.findOrCreateVersion(volumeUuid);
23354            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23355        }
23356
23357        for (PackageSetting ps : packages) {
23358            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23359            synchronized (mInstallLock) {
23360                final PackageParser.Package pkg;
23361                try {
23362                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23363                    loaded.add(pkg.applicationInfo);
23364
23365                } catch (PackageManagerException e) {
23366                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23367                }
23368
23369                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23370                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23371                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23372                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23373                }
23374            }
23375        }
23376
23377        // Reconcile app data for all started/unlocked users
23378        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23379        final UserManager um = mContext.getSystemService(UserManager.class);
23380        UserManagerInternal umInternal = getUserManagerInternal();
23381        for (UserInfo user : um.getUsers()) {
23382            final int flags;
23383            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23384                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23385            } else if (umInternal.isUserRunning(user.id)) {
23386                flags = StorageManager.FLAG_STORAGE_DE;
23387            } else {
23388                continue;
23389            }
23390
23391            try {
23392                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23393                synchronized (mInstallLock) {
23394                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23395                }
23396            } catch (IllegalStateException e) {
23397                // Device was probably ejected, and we'll process that event momentarily
23398                Slog.w(TAG, "Failed to prepare storage: " + e);
23399            }
23400        }
23401
23402        synchronized (mPackages) {
23403            int updateFlags = UPDATE_PERMISSIONS_ALL;
23404            if (ver.sdkVersion != mSdkVersion) {
23405                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23406                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23407                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23408            }
23409            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23410
23411            // Yay, everything is now upgraded
23412            ver.forceCurrent();
23413
23414            mSettings.writeLPr();
23415        }
23416
23417        for (PackageFreezer freezer : freezers) {
23418            freezer.close();
23419        }
23420
23421        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23422        sendResourcesChangedBroadcast(true, false, loaded, null);
23423        mLoadedVolumes.add(vol.getId());
23424    }
23425
23426    private void unloadPrivatePackages(final VolumeInfo vol) {
23427        mHandler.post(new Runnable() {
23428            @Override
23429            public void run() {
23430                unloadPrivatePackagesInner(vol);
23431            }
23432        });
23433    }
23434
23435    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23436        final String volumeUuid = vol.fsUuid;
23437        if (TextUtils.isEmpty(volumeUuid)) {
23438            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23439            return;
23440        }
23441
23442        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23443        synchronized (mInstallLock) {
23444        synchronized (mPackages) {
23445            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23446            for (PackageSetting ps : packages) {
23447                if (ps.pkg == null) continue;
23448
23449                final ApplicationInfo info = ps.pkg.applicationInfo;
23450                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23451                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23452
23453                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23454                        "unloadPrivatePackagesInner")) {
23455                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23456                            false, null)) {
23457                        unloaded.add(info);
23458                    } else {
23459                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23460                    }
23461                }
23462
23463                // Try very hard to release any references to this package
23464                // so we don't risk the system server being killed due to
23465                // open FDs
23466                AttributeCache.instance().removePackage(ps.name);
23467            }
23468
23469            mSettings.writeLPr();
23470        }
23471        }
23472
23473        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23474        sendResourcesChangedBroadcast(false, false, unloaded, null);
23475        mLoadedVolumes.remove(vol.getId());
23476
23477        // Try very hard to release any references to this path so we don't risk
23478        // the system server being killed due to open FDs
23479        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23480
23481        for (int i = 0; i < 3; i++) {
23482            System.gc();
23483            System.runFinalization();
23484        }
23485    }
23486
23487    private void assertPackageKnown(String volumeUuid, String packageName)
23488            throws PackageManagerException {
23489        synchronized (mPackages) {
23490            // Normalize package name to handle renamed packages
23491            packageName = normalizePackageNameLPr(packageName);
23492
23493            final PackageSetting ps = mSettings.mPackages.get(packageName);
23494            if (ps == null) {
23495                throw new PackageManagerException("Package " + packageName + " is unknown");
23496            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23497                throw new PackageManagerException(
23498                        "Package " + packageName + " found on unknown volume " + volumeUuid
23499                                + "; expected volume " + ps.volumeUuid);
23500            }
23501        }
23502    }
23503
23504    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23505            throws PackageManagerException {
23506        synchronized (mPackages) {
23507            // Normalize package name to handle renamed packages
23508            packageName = normalizePackageNameLPr(packageName);
23509
23510            final PackageSetting ps = mSettings.mPackages.get(packageName);
23511            if (ps == null) {
23512                throw new PackageManagerException("Package " + packageName + " is unknown");
23513            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23514                throw new PackageManagerException(
23515                        "Package " + packageName + " found on unknown volume " + volumeUuid
23516                                + "; expected volume " + ps.volumeUuid);
23517            } else if (!ps.getInstalled(userId)) {
23518                throw new PackageManagerException(
23519                        "Package " + packageName + " not installed for user " + userId);
23520            }
23521        }
23522    }
23523
23524    private List<String> collectAbsoluteCodePaths() {
23525        synchronized (mPackages) {
23526            List<String> codePaths = new ArrayList<>();
23527            final int packageCount = mSettings.mPackages.size();
23528            for (int i = 0; i < packageCount; i++) {
23529                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23530                codePaths.add(ps.codePath.getAbsolutePath());
23531            }
23532            return codePaths;
23533        }
23534    }
23535
23536    /**
23537     * Examine all apps present on given mounted volume, and destroy apps that
23538     * aren't expected, either due to uninstallation or reinstallation on
23539     * another volume.
23540     */
23541    private void reconcileApps(String volumeUuid) {
23542        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23543        List<File> filesToDelete = null;
23544
23545        final File[] files = FileUtils.listFilesOrEmpty(
23546                Environment.getDataAppDirectory(volumeUuid));
23547        for (File file : files) {
23548            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23549                    && !PackageInstallerService.isStageName(file.getName());
23550            if (!isPackage) {
23551                // Ignore entries which are not packages
23552                continue;
23553            }
23554
23555            String absolutePath = file.getAbsolutePath();
23556
23557            boolean pathValid = false;
23558            final int absoluteCodePathCount = absoluteCodePaths.size();
23559            for (int i = 0; i < absoluteCodePathCount; i++) {
23560                String absoluteCodePath = absoluteCodePaths.get(i);
23561                if (absolutePath.startsWith(absoluteCodePath)) {
23562                    pathValid = true;
23563                    break;
23564                }
23565            }
23566
23567            if (!pathValid) {
23568                if (filesToDelete == null) {
23569                    filesToDelete = new ArrayList<>();
23570                }
23571                filesToDelete.add(file);
23572            }
23573        }
23574
23575        if (filesToDelete != null) {
23576            final int fileToDeleteCount = filesToDelete.size();
23577            for (int i = 0; i < fileToDeleteCount; i++) {
23578                File fileToDelete = filesToDelete.get(i);
23579                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23580                synchronized (mInstallLock) {
23581                    removeCodePathLI(fileToDelete);
23582                }
23583            }
23584        }
23585    }
23586
23587    /**
23588     * Reconcile all app data for the given user.
23589     * <p>
23590     * Verifies that directories exist and that ownership and labeling is
23591     * correct for all installed apps on all mounted volumes.
23592     */
23593    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23594        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23595        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23596            final String volumeUuid = vol.getFsUuid();
23597            synchronized (mInstallLock) {
23598                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23599            }
23600        }
23601    }
23602
23603    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23604            boolean migrateAppData) {
23605        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23606    }
23607
23608    /**
23609     * Reconcile all app data on given mounted volume.
23610     * <p>
23611     * Destroys app data that isn't expected, either due to uninstallation or
23612     * reinstallation on another volume.
23613     * <p>
23614     * Verifies that directories exist and that ownership and labeling is
23615     * correct for all installed apps.
23616     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23617     */
23618    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23619            boolean migrateAppData, boolean onlyCoreApps) {
23620        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23621                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23622        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23623
23624        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23625        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23626
23627        // First look for stale data that doesn't belong, and check if things
23628        // have changed since we did our last restorecon
23629        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23630            if (StorageManager.isFileEncryptedNativeOrEmulated()
23631                    && !StorageManager.isUserKeyUnlocked(userId)) {
23632                throw new RuntimeException(
23633                        "Yikes, someone asked us to reconcile CE storage while " + userId
23634                                + " was still locked; this would have caused massive data loss!");
23635            }
23636
23637            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23638            for (File file : files) {
23639                final String packageName = file.getName();
23640                try {
23641                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23642                } catch (PackageManagerException e) {
23643                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23644                    try {
23645                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23646                                StorageManager.FLAG_STORAGE_CE, 0);
23647                    } catch (InstallerException e2) {
23648                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23649                    }
23650                }
23651            }
23652        }
23653        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23654            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23655            for (File file : files) {
23656                final String packageName = file.getName();
23657                try {
23658                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23659                } catch (PackageManagerException e) {
23660                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23661                    try {
23662                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23663                                StorageManager.FLAG_STORAGE_DE, 0);
23664                    } catch (InstallerException e2) {
23665                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23666                    }
23667                }
23668            }
23669        }
23670
23671        // Ensure that data directories are ready to roll for all packages
23672        // installed for this volume and user
23673        final List<PackageSetting> packages;
23674        synchronized (mPackages) {
23675            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23676        }
23677        int preparedCount = 0;
23678        for (PackageSetting ps : packages) {
23679            final String packageName = ps.name;
23680            if (ps.pkg == null) {
23681                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23682                // TODO: might be due to legacy ASEC apps; we should circle back
23683                // and reconcile again once they're scanned
23684                continue;
23685            }
23686            // Skip non-core apps if requested
23687            if (onlyCoreApps && !ps.pkg.coreApp) {
23688                result.add(packageName);
23689                continue;
23690            }
23691
23692            if (ps.getInstalled(userId)) {
23693                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23694                preparedCount++;
23695            }
23696        }
23697
23698        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23699        return result;
23700    }
23701
23702    /**
23703     * Prepare app data for the given app just after it was installed or
23704     * upgraded. This method carefully only touches users that it's installed
23705     * for, and it forces a restorecon to handle any seinfo changes.
23706     * <p>
23707     * Verifies that directories exist and that ownership and labeling is
23708     * correct for all installed apps. If there is an ownership mismatch, it
23709     * will try recovering system apps by wiping data; third-party app data is
23710     * left intact.
23711     * <p>
23712     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23713     */
23714    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23715        final PackageSetting ps;
23716        synchronized (mPackages) {
23717            ps = mSettings.mPackages.get(pkg.packageName);
23718            mSettings.writeKernelMappingLPr(ps);
23719        }
23720
23721        final UserManager um = mContext.getSystemService(UserManager.class);
23722        UserManagerInternal umInternal = getUserManagerInternal();
23723        for (UserInfo user : um.getUsers()) {
23724            final int flags;
23725            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23726                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23727            } else if (umInternal.isUserRunning(user.id)) {
23728                flags = StorageManager.FLAG_STORAGE_DE;
23729            } else {
23730                continue;
23731            }
23732
23733            if (ps.getInstalled(user.id)) {
23734                // TODO: when user data is locked, mark that we're still dirty
23735                prepareAppDataLIF(pkg, user.id, flags);
23736            }
23737        }
23738    }
23739
23740    /**
23741     * Prepare app data for the given app.
23742     * <p>
23743     * Verifies that directories exist and that ownership and labeling is
23744     * correct for all installed apps. If there is an ownership mismatch, this
23745     * will try recovering system apps by wiping data; third-party app data is
23746     * left intact.
23747     */
23748    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23749        if (pkg == null) {
23750            Slog.wtf(TAG, "Package was null!", new Throwable());
23751            return;
23752        }
23753        prepareAppDataLeafLIF(pkg, userId, flags);
23754        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23755        for (int i = 0; i < childCount; i++) {
23756            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23757        }
23758    }
23759
23760    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23761            boolean maybeMigrateAppData) {
23762        prepareAppDataLIF(pkg, userId, flags);
23763
23764        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23765            // We may have just shuffled around app data directories, so
23766            // prepare them one more time
23767            prepareAppDataLIF(pkg, userId, flags);
23768        }
23769    }
23770
23771    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23772        if (DEBUG_APP_DATA) {
23773            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23774                    + Integer.toHexString(flags));
23775        }
23776
23777        final String volumeUuid = pkg.volumeUuid;
23778        final String packageName = pkg.packageName;
23779        final ApplicationInfo app = pkg.applicationInfo;
23780        final int appId = UserHandle.getAppId(app.uid);
23781
23782        Preconditions.checkNotNull(app.seInfo);
23783
23784        long ceDataInode = -1;
23785        try {
23786            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23787                    appId, app.seInfo, app.targetSdkVersion);
23788        } catch (InstallerException e) {
23789            if (app.isSystemApp()) {
23790                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23791                        + ", but trying to recover: " + e);
23792                destroyAppDataLeafLIF(pkg, userId, flags);
23793                try {
23794                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23795                            appId, app.seInfo, app.targetSdkVersion);
23796                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23797                } catch (InstallerException e2) {
23798                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23799                }
23800            } else {
23801                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23802            }
23803        }
23804
23805        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23806            // TODO: mark this structure as dirty so we persist it!
23807            synchronized (mPackages) {
23808                final PackageSetting ps = mSettings.mPackages.get(packageName);
23809                if (ps != null) {
23810                    ps.setCeDataInode(ceDataInode, userId);
23811                }
23812            }
23813        }
23814
23815        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23816    }
23817
23818    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23819        if (pkg == null) {
23820            Slog.wtf(TAG, "Package was null!", new Throwable());
23821            return;
23822        }
23823        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23824        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23825        for (int i = 0; i < childCount; i++) {
23826            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23827        }
23828    }
23829
23830    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23831        final String volumeUuid = pkg.volumeUuid;
23832        final String packageName = pkg.packageName;
23833        final ApplicationInfo app = pkg.applicationInfo;
23834
23835        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23836            // Create a native library symlink only if we have native libraries
23837            // and if the native libraries are 32 bit libraries. We do not provide
23838            // this symlink for 64 bit libraries.
23839            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23840                final String nativeLibPath = app.nativeLibraryDir;
23841                try {
23842                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23843                            nativeLibPath, userId);
23844                } catch (InstallerException e) {
23845                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23846                }
23847            }
23848        }
23849    }
23850
23851    /**
23852     * For system apps on non-FBE devices, this method migrates any existing
23853     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23854     * requested by the app.
23855     */
23856    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23857        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23858                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23859            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23860                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23861            try {
23862                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23863                        storageTarget);
23864            } catch (InstallerException e) {
23865                logCriticalInfo(Log.WARN,
23866                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23867            }
23868            return true;
23869        } else {
23870            return false;
23871        }
23872    }
23873
23874    public PackageFreezer freezePackage(String packageName, String killReason) {
23875        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23876    }
23877
23878    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23879        return new PackageFreezer(packageName, userId, killReason);
23880    }
23881
23882    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23883            String killReason) {
23884        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23885    }
23886
23887    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23888            String killReason) {
23889        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23890            return new PackageFreezer();
23891        } else {
23892            return freezePackage(packageName, userId, killReason);
23893        }
23894    }
23895
23896    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23897            String killReason) {
23898        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23899    }
23900
23901    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23902            String killReason) {
23903        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23904            return new PackageFreezer();
23905        } else {
23906            return freezePackage(packageName, userId, killReason);
23907        }
23908    }
23909
23910    /**
23911     * Class that freezes and kills the given package upon creation, and
23912     * unfreezes it upon closing. This is typically used when doing surgery on
23913     * app code/data to prevent the app from running while you're working.
23914     */
23915    private class PackageFreezer implements AutoCloseable {
23916        private final String mPackageName;
23917        private final PackageFreezer[] mChildren;
23918
23919        private final boolean mWeFroze;
23920
23921        private final AtomicBoolean mClosed = new AtomicBoolean();
23922        private final CloseGuard mCloseGuard = CloseGuard.get();
23923
23924        /**
23925         * Create and return a stub freezer that doesn't actually do anything,
23926         * typically used when someone requested
23927         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23928         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23929         */
23930        public PackageFreezer() {
23931            mPackageName = null;
23932            mChildren = null;
23933            mWeFroze = false;
23934            mCloseGuard.open("close");
23935        }
23936
23937        public PackageFreezer(String packageName, int userId, String killReason) {
23938            synchronized (mPackages) {
23939                mPackageName = packageName;
23940                mWeFroze = mFrozenPackages.add(mPackageName);
23941
23942                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23943                if (ps != null) {
23944                    killApplication(ps.name, ps.appId, userId, killReason);
23945                }
23946
23947                final PackageParser.Package p = mPackages.get(packageName);
23948                if (p != null && p.childPackages != null) {
23949                    final int N = p.childPackages.size();
23950                    mChildren = new PackageFreezer[N];
23951                    for (int i = 0; i < N; i++) {
23952                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23953                                userId, killReason);
23954                    }
23955                } else {
23956                    mChildren = null;
23957                }
23958            }
23959            mCloseGuard.open("close");
23960        }
23961
23962        @Override
23963        protected void finalize() throws Throwable {
23964            try {
23965                if (mCloseGuard != null) {
23966                    mCloseGuard.warnIfOpen();
23967                }
23968
23969                close();
23970            } finally {
23971                super.finalize();
23972            }
23973        }
23974
23975        @Override
23976        public void close() {
23977            mCloseGuard.close();
23978            if (mClosed.compareAndSet(false, true)) {
23979                synchronized (mPackages) {
23980                    if (mWeFroze) {
23981                        mFrozenPackages.remove(mPackageName);
23982                    }
23983
23984                    if (mChildren != null) {
23985                        for (PackageFreezer freezer : mChildren) {
23986                            freezer.close();
23987                        }
23988                    }
23989                }
23990            }
23991        }
23992    }
23993
23994    /**
23995     * Verify that given package is currently frozen.
23996     */
23997    private void checkPackageFrozen(String packageName) {
23998        synchronized (mPackages) {
23999            if (!mFrozenPackages.contains(packageName)) {
24000                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
24001            }
24002        }
24003    }
24004
24005    @Override
24006    public int movePackage(final String packageName, final String volumeUuid) {
24007        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24008
24009        final int callingUid = Binder.getCallingUid();
24010        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
24011        final int moveId = mNextMoveId.getAndIncrement();
24012        mHandler.post(new Runnable() {
24013            @Override
24014            public void run() {
24015                try {
24016                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
24017                } catch (PackageManagerException e) {
24018                    Slog.w(TAG, "Failed to move " + packageName, e);
24019                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
24020                }
24021            }
24022        });
24023        return moveId;
24024    }
24025
24026    private void movePackageInternal(final String packageName, final String volumeUuid,
24027            final int moveId, final int callingUid, UserHandle user)
24028                    throws PackageManagerException {
24029        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24030        final PackageManager pm = mContext.getPackageManager();
24031
24032        final boolean currentAsec;
24033        final String currentVolumeUuid;
24034        final File codeFile;
24035        final String installerPackageName;
24036        final String packageAbiOverride;
24037        final int appId;
24038        final String seinfo;
24039        final String label;
24040        final int targetSdkVersion;
24041        final PackageFreezer freezer;
24042        final int[] installedUserIds;
24043
24044        // reader
24045        synchronized (mPackages) {
24046            final PackageParser.Package pkg = mPackages.get(packageName);
24047            final PackageSetting ps = mSettings.mPackages.get(packageName);
24048            if (pkg == null
24049                    || ps == null
24050                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
24051                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
24052            }
24053            if (pkg.applicationInfo.isSystemApp()) {
24054                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
24055                        "Cannot move system application");
24056            }
24057
24058            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
24059            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
24060                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
24061            if (isInternalStorage && !allow3rdPartyOnInternal) {
24062                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
24063                        "3rd party apps are not allowed on internal storage");
24064            }
24065
24066            if (pkg.applicationInfo.isExternalAsec()) {
24067                currentAsec = true;
24068                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
24069            } else if (pkg.applicationInfo.isForwardLocked()) {
24070                currentAsec = true;
24071                currentVolumeUuid = "forward_locked";
24072            } else {
24073                currentAsec = false;
24074                currentVolumeUuid = ps.volumeUuid;
24075
24076                final File probe = new File(pkg.codePath);
24077                final File probeOat = new File(probe, "oat");
24078                if (!probe.isDirectory() || !probeOat.isDirectory()) {
24079                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24080                            "Move only supported for modern cluster style installs");
24081                }
24082            }
24083
24084            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
24085                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24086                        "Package already moved to " + volumeUuid);
24087            }
24088            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
24089                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
24090                        "Device admin cannot be moved");
24091            }
24092
24093            if (mFrozenPackages.contains(packageName)) {
24094                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
24095                        "Failed to move already frozen package");
24096            }
24097
24098            codeFile = new File(pkg.codePath);
24099            installerPackageName = ps.installerPackageName;
24100            packageAbiOverride = ps.cpuAbiOverrideString;
24101            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
24102            seinfo = pkg.applicationInfo.seInfo;
24103            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
24104            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
24105            freezer = freezePackage(packageName, "movePackageInternal");
24106            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
24107        }
24108
24109        final Bundle extras = new Bundle();
24110        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
24111        extras.putString(Intent.EXTRA_TITLE, label);
24112        mMoveCallbacks.notifyCreated(moveId, extras);
24113
24114        int installFlags;
24115        final boolean moveCompleteApp;
24116        final File measurePath;
24117
24118        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
24119            installFlags = INSTALL_INTERNAL;
24120            moveCompleteApp = !currentAsec;
24121            measurePath = Environment.getDataAppDirectory(volumeUuid);
24122        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
24123            installFlags = INSTALL_EXTERNAL;
24124            moveCompleteApp = false;
24125            measurePath = storage.getPrimaryPhysicalVolume().getPath();
24126        } else {
24127            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
24128            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
24129                    || !volume.isMountedWritable()) {
24130                freezer.close();
24131                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24132                        "Move location not mounted private volume");
24133            }
24134
24135            Preconditions.checkState(!currentAsec);
24136
24137            installFlags = INSTALL_INTERNAL;
24138            moveCompleteApp = true;
24139            measurePath = Environment.getDataAppDirectory(volumeUuid);
24140        }
24141
24142        // If we're moving app data around, we need all the users unlocked
24143        if (moveCompleteApp) {
24144            for (int userId : installedUserIds) {
24145                if (StorageManager.isFileEncryptedNativeOrEmulated()
24146                        && !StorageManager.isUserKeyUnlocked(userId)) {
24147                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
24148                            "User " + userId + " must be unlocked");
24149                }
24150            }
24151        }
24152
24153        final PackageStats stats = new PackageStats(null, -1);
24154        synchronized (mInstaller) {
24155            for (int userId : installedUserIds) {
24156                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
24157                    freezer.close();
24158                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24159                            "Failed to measure package size");
24160                }
24161            }
24162        }
24163
24164        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
24165                + stats.dataSize);
24166
24167        final long startFreeBytes = measurePath.getUsableSpace();
24168        final long sizeBytes;
24169        if (moveCompleteApp) {
24170            sizeBytes = stats.codeSize + stats.dataSize;
24171        } else {
24172            sizeBytes = stats.codeSize;
24173        }
24174
24175        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
24176            freezer.close();
24177            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
24178                    "Not enough free space to move");
24179        }
24180
24181        mMoveCallbacks.notifyStatusChanged(moveId, 10);
24182
24183        final CountDownLatch installedLatch = new CountDownLatch(1);
24184        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
24185            @Override
24186            public void onUserActionRequired(Intent intent) throws RemoteException {
24187                throw new IllegalStateException();
24188            }
24189
24190            @Override
24191            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
24192                    Bundle extras) throws RemoteException {
24193                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
24194                        + PackageManager.installStatusToString(returnCode, msg));
24195
24196                installedLatch.countDown();
24197                freezer.close();
24198
24199                final int status = PackageManager.installStatusToPublicStatus(returnCode);
24200                switch (status) {
24201                    case PackageInstaller.STATUS_SUCCESS:
24202                        mMoveCallbacks.notifyStatusChanged(moveId,
24203                                PackageManager.MOVE_SUCCEEDED);
24204                        break;
24205                    case PackageInstaller.STATUS_FAILURE_STORAGE:
24206                        mMoveCallbacks.notifyStatusChanged(moveId,
24207                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
24208                        break;
24209                    default:
24210                        mMoveCallbacks.notifyStatusChanged(moveId,
24211                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
24212                        break;
24213                }
24214            }
24215        };
24216
24217        final MoveInfo move;
24218        if (moveCompleteApp) {
24219            // Kick off a thread to report progress estimates
24220            new Thread() {
24221                @Override
24222                public void run() {
24223                    while (true) {
24224                        try {
24225                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
24226                                break;
24227                            }
24228                        } catch (InterruptedException ignored) {
24229                        }
24230
24231                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
24232                        final int progress = 10 + (int) MathUtils.constrain(
24233                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
24234                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
24235                    }
24236                }
24237            }.start();
24238
24239            final String dataAppName = codeFile.getName();
24240            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
24241                    dataAppName, appId, seinfo, targetSdkVersion);
24242        } else {
24243            move = null;
24244        }
24245
24246        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
24247
24248        final Message msg = mHandler.obtainMessage(INIT_COPY);
24249        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
24250        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
24251                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
24252                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
24253                PackageManager.INSTALL_REASON_UNKNOWN);
24254        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
24255        msg.obj = params;
24256
24257        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
24258                System.identityHashCode(msg.obj));
24259        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
24260                System.identityHashCode(msg.obj));
24261
24262        mHandler.sendMessage(msg);
24263    }
24264
24265    @Override
24266    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
24267        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
24268
24269        final int realMoveId = mNextMoveId.getAndIncrement();
24270        final Bundle extras = new Bundle();
24271        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
24272        mMoveCallbacks.notifyCreated(realMoveId, extras);
24273
24274        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
24275            @Override
24276            public void onCreated(int moveId, Bundle extras) {
24277                // Ignored
24278            }
24279
24280            @Override
24281            public void onStatusChanged(int moveId, int status, long estMillis) {
24282                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
24283            }
24284        };
24285
24286        final StorageManager storage = mContext.getSystemService(StorageManager.class);
24287        storage.setPrimaryStorageUuid(volumeUuid, callback);
24288        return realMoveId;
24289    }
24290
24291    @Override
24292    public int getMoveStatus(int moveId) {
24293        mContext.enforceCallingOrSelfPermission(
24294                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24295        return mMoveCallbacks.mLastStatus.get(moveId);
24296    }
24297
24298    @Override
24299    public void registerMoveCallback(IPackageMoveObserver callback) {
24300        mContext.enforceCallingOrSelfPermission(
24301                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24302        mMoveCallbacks.register(callback);
24303    }
24304
24305    @Override
24306    public void unregisterMoveCallback(IPackageMoveObserver callback) {
24307        mContext.enforceCallingOrSelfPermission(
24308                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
24309        mMoveCallbacks.unregister(callback);
24310    }
24311
24312    @Override
24313    public boolean setInstallLocation(int loc) {
24314        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
24315                null);
24316        if (getInstallLocation() == loc) {
24317            return true;
24318        }
24319        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
24320                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
24321            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
24322                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
24323            return true;
24324        }
24325        return false;
24326   }
24327
24328    @Override
24329    public int getInstallLocation() {
24330        // allow instant app access
24331        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
24332                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
24333                PackageHelper.APP_INSTALL_AUTO);
24334    }
24335
24336    /** Called by UserManagerService */
24337    void cleanUpUser(UserManagerService userManager, int userHandle) {
24338        synchronized (mPackages) {
24339            mDirtyUsers.remove(userHandle);
24340            mUserNeedsBadging.delete(userHandle);
24341            mSettings.removeUserLPw(userHandle);
24342            mPendingBroadcasts.remove(userHandle);
24343            mInstantAppRegistry.onUserRemovedLPw(userHandle);
24344            removeUnusedPackagesLPw(userManager, userHandle);
24345        }
24346    }
24347
24348    /**
24349     * We're removing userHandle and would like to remove any downloaded packages
24350     * that are no longer in use by any other user.
24351     * @param userHandle the user being removed
24352     */
24353    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
24354        final boolean DEBUG_CLEAN_APKS = false;
24355        int [] users = userManager.getUserIds();
24356        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
24357        while (psit.hasNext()) {
24358            PackageSetting ps = psit.next();
24359            if (ps.pkg == null) {
24360                continue;
24361            }
24362            final String packageName = ps.pkg.packageName;
24363            // Skip over if system app
24364            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24365                continue;
24366            }
24367            if (DEBUG_CLEAN_APKS) {
24368                Slog.i(TAG, "Checking package " + packageName);
24369            }
24370            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24371            if (keep) {
24372                if (DEBUG_CLEAN_APKS) {
24373                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24374                }
24375            } else {
24376                for (int i = 0; i < users.length; i++) {
24377                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24378                        keep = true;
24379                        if (DEBUG_CLEAN_APKS) {
24380                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24381                                    + users[i]);
24382                        }
24383                        break;
24384                    }
24385                }
24386            }
24387            if (!keep) {
24388                if (DEBUG_CLEAN_APKS) {
24389                    Slog.i(TAG, "  Removing package " + packageName);
24390                }
24391                mHandler.post(new Runnable() {
24392                    public void run() {
24393                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24394                                userHandle, 0);
24395                    } //end run
24396                });
24397            }
24398        }
24399    }
24400
24401    /** Called by UserManagerService */
24402    void createNewUser(int userId, String[] disallowedPackages) {
24403        synchronized (mInstallLock) {
24404            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24405        }
24406        synchronized (mPackages) {
24407            scheduleWritePackageRestrictionsLocked(userId);
24408            scheduleWritePackageListLocked(userId);
24409            applyFactoryDefaultBrowserLPw(userId);
24410            primeDomainVerificationsLPw(userId);
24411        }
24412    }
24413
24414    void onNewUserCreated(final int userId) {
24415        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24416        // If permission review for legacy apps is required, we represent
24417        // dagerous permissions for such apps as always granted runtime
24418        // permissions to keep per user flag state whether review is needed.
24419        // Hence, if a new user is added we have to propagate dangerous
24420        // permission grants for these legacy apps.
24421        if (mPermissionReviewRequired) {
24422            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24423                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24424        }
24425    }
24426
24427    @Override
24428    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24429        mContext.enforceCallingOrSelfPermission(
24430                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24431                "Only package verification agents can read the verifier device identity");
24432
24433        synchronized (mPackages) {
24434            return mSettings.getVerifierDeviceIdentityLPw();
24435        }
24436    }
24437
24438    @Override
24439    public void setPermissionEnforced(String permission, boolean enforced) {
24440        // TODO: Now that we no longer change GID for storage, this should to away.
24441        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24442                "setPermissionEnforced");
24443        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24444            synchronized (mPackages) {
24445                if (mSettings.mReadExternalStorageEnforced == null
24446                        || mSettings.mReadExternalStorageEnforced != enforced) {
24447                    mSettings.mReadExternalStorageEnforced = enforced;
24448                    mSettings.writeLPr();
24449                }
24450            }
24451            // kill any non-foreground processes so we restart them and
24452            // grant/revoke the GID.
24453            final IActivityManager am = ActivityManager.getService();
24454            if (am != null) {
24455                final long token = Binder.clearCallingIdentity();
24456                try {
24457                    am.killProcessesBelowForeground("setPermissionEnforcement");
24458                } catch (RemoteException e) {
24459                } finally {
24460                    Binder.restoreCallingIdentity(token);
24461                }
24462            }
24463        } else {
24464            throw new IllegalArgumentException("No selective enforcement for " + permission);
24465        }
24466    }
24467
24468    @Override
24469    @Deprecated
24470    public boolean isPermissionEnforced(String permission) {
24471        // allow instant applications
24472        return true;
24473    }
24474
24475    @Override
24476    public boolean isStorageLow() {
24477        // allow instant applications
24478        final long token = Binder.clearCallingIdentity();
24479        try {
24480            final DeviceStorageMonitorInternal
24481                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24482            if (dsm != null) {
24483                return dsm.isMemoryLow();
24484            } else {
24485                return false;
24486            }
24487        } finally {
24488            Binder.restoreCallingIdentity(token);
24489        }
24490    }
24491
24492    @Override
24493    public IPackageInstaller getPackageInstaller() {
24494        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24495            return null;
24496        }
24497        return mInstallerService;
24498    }
24499
24500    private boolean userNeedsBadging(int userId) {
24501        int index = mUserNeedsBadging.indexOfKey(userId);
24502        if (index < 0) {
24503            final UserInfo userInfo;
24504            final long token = Binder.clearCallingIdentity();
24505            try {
24506                userInfo = sUserManager.getUserInfo(userId);
24507            } finally {
24508                Binder.restoreCallingIdentity(token);
24509            }
24510            final boolean b;
24511            if (userInfo != null && userInfo.isManagedProfile()) {
24512                b = true;
24513            } else {
24514                b = false;
24515            }
24516            mUserNeedsBadging.put(userId, b);
24517            return b;
24518        }
24519        return mUserNeedsBadging.valueAt(index);
24520    }
24521
24522    @Override
24523    public KeySet getKeySetByAlias(String packageName, String alias) {
24524        if (packageName == null || alias == null) {
24525            return null;
24526        }
24527        synchronized(mPackages) {
24528            final PackageParser.Package pkg = mPackages.get(packageName);
24529            if (pkg == null) {
24530                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24531                throw new IllegalArgumentException("Unknown package: " + packageName);
24532            }
24533            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24534            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24535                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24536                throw new IllegalArgumentException("Unknown package: " + packageName);
24537            }
24538            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24539            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24540        }
24541    }
24542
24543    @Override
24544    public KeySet getSigningKeySet(String packageName) {
24545        if (packageName == null) {
24546            return null;
24547        }
24548        synchronized(mPackages) {
24549            final int callingUid = Binder.getCallingUid();
24550            final int callingUserId = UserHandle.getUserId(callingUid);
24551            final PackageParser.Package pkg = mPackages.get(packageName);
24552            if (pkg == null) {
24553                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24554                throw new IllegalArgumentException("Unknown package: " + packageName);
24555            }
24556            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24557            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24558                // filter and pretend the package doesn't exist
24559                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24560                        + ", uid:" + callingUid);
24561                throw new IllegalArgumentException("Unknown package: " + packageName);
24562            }
24563            if (pkg.applicationInfo.uid != callingUid
24564                    && Process.SYSTEM_UID != callingUid) {
24565                throw new SecurityException("May not access signing KeySet of other apps.");
24566            }
24567            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24568            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24569        }
24570    }
24571
24572    @Override
24573    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24574        final int callingUid = Binder.getCallingUid();
24575        if (getInstantAppPackageName(callingUid) != null) {
24576            return false;
24577        }
24578        if (packageName == null || ks == null) {
24579            return false;
24580        }
24581        synchronized(mPackages) {
24582            final PackageParser.Package pkg = mPackages.get(packageName);
24583            if (pkg == null
24584                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24585                            UserHandle.getUserId(callingUid))) {
24586                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24587                throw new IllegalArgumentException("Unknown package: " + packageName);
24588            }
24589            IBinder ksh = ks.getToken();
24590            if (ksh instanceof KeySetHandle) {
24591                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24592                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24593            }
24594            return false;
24595        }
24596    }
24597
24598    @Override
24599    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24600        final int callingUid = Binder.getCallingUid();
24601        if (getInstantAppPackageName(callingUid) != null) {
24602            return false;
24603        }
24604        if (packageName == null || ks == null) {
24605            return false;
24606        }
24607        synchronized(mPackages) {
24608            final PackageParser.Package pkg = mPackages.get(packageName);
24609            if (pkg == null
24610                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24611                            UserHandle.getUserId(callingUid))) {
24612                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24613                throw new IllegalArgumentException("Unknown package: " + packageName);
24614            }
24615            IBinder ksh = ks.getToken();
24616            if (ksh instanceof KeySetHandle) {
24617                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24618                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24619            }
24620            return false;
24621        }
24622    }
24623
24624    private void deletePackageIfUnusedLPr(final String packageName) {
24625        PackageSetting ps = mSettings.mPackages.get(packageName);
24626        if (ps == null) {
24627            return;
24628        }
24629        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24630            // TODO Implement atomic delete if package is unused
24631            // It is currently possible that the package will be deleted even if it is installed
24632            // after this method returns.
24633            mHandler.post(new Runnable() {
24634                public void run() {
24635                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24636                            0, PackageManager.DELETE_ALL_USERS);
24637                }
24638            });
24639        }
24640    }
24641
24642    /**
24643     * Check and throw if the given before/after packages would be considered a
24644     * downgrade.
24645     */
24646    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24647            throws PackageManagerException {
24648        if (after.versionCode < before.mVersionCode) {
24649            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24650                    "Update version code " + after.versionCode + " is older than current "
24651                    + before.mVersionCode);
24652        } else if (after.versionCode == before.mVersionCode) {
24653            if (after.baseRevisionCode < before.baseRevisionCode) {
24654                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24655                        "Update base revision code " + after.baseRevisionCode
24656                        + " is older than current " + before.baseRevisionCode);
24657            }
24658
24659            if (!ArrayUtils.isEmpty(after.splitNames)) {
24660                for (int i = 0; i < after.splitNames.length; i++) {
24661                    final String splitName = after.splitNames[i];
24662                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24663                    if (j != -1) {
24664                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24665                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24666                                    "Update split " + splitName + " revision code "
24667                                    + after.splitRevisionCodes[i] + " is older than current "
24668                                    + before.splitRevisionCodes[j]);
24669                        }
24670                    }
24671                }
24672            }
24673        }
24674    }
24675
24676    private static class MoveCallbacks extends Handler {
24677        private static final int MSG_CREATED = 1;
24678        private static final int MSG_STATUS_CHANGED = 2;
24679
24680        private final RemoteCallbackList<IPackageMoveObserver>
24681                mCallbacks = new RemoteCallbackList<>();
24682
24683        private final SparseIntArray mLastStatus = new SparseIntArray();
24684
24685        public MoveCallbacks(Looper looper) {
24686            super(looper);
24687        }
24688
24689        public void register(IPackageMoveObserver callback) {
24690            mCallbacks.register(callback);
24691        }
24692
24693        public void unregister(IPackageMoveObserver callback) {
24694            mCallbacks.unregister(callback);
24695        }
24696
24697        @Override
24698        public void handleMessage(Message msg) {
24699            final SomeArgs args = (SomeArgs) msg.obj;
24700            final int n = mCallbacks.beginBroadcast();
24701            for (int i = 0; i < n; i++) {
24702                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24703                try {
24704                    invokeCallback(callback, msg.what, args);
24705                } catch (RemoteException ignored) {
24706                }
24707            }
24708            mCallbacks.finishBroadcast();
24709            args.recycle();
24710        }
24711
24712        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24713                throws RemoteException {
24714            switch (what) {
24715                case MSG_CREATED: {
24716                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24717                    break;
24718                }
24719                case MSG_STATUS_CHANGED: {
24720                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24721                    break;
24722                }
24723            }
24724        }
24725
24726        private void notifyCreated(int moveId, Bundle extras) {
24727            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24728
24729            final SomeArgs args = SomeArgs.obtain();
24730            args.argi1 = moveId;
24731            args.arg2 = extras;
24732            obtainMessage(MSG_CREATED, args).sendToTarget();
24733        }
24734
24735        private void notifyStatusChanged(int moveId, int status) {
24736            notifyStatusChanged(moveId, status, -1);
24737        }
24738
24739        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24740            Slog.v(TAG, "Move " + moveId + " status " + status);
24741
24742            final SomeArgs args = SomeArgs.obtain();
24743            args.argi1 = moveId;
24744            args.argi2 = status;
24745            args.arg3 = estMillis;
24746            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24747
24748            synchronized (mLastStatus) {
24749                mLastStatus.put(moveId, status);
24750            }
24751        }
24752    }
24753
24754    private final static class OnPermissionChangeListeners extends Handler {
24755        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24756
24757        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24758                new RemoteCallbackList<>();
24759
24760        public OnPermissionChangeListeners(Looper looper) {
24761            super(looper);
24762        }
24763
24764        @Override
24765        public void handleMessage(Message msg) {
24766            switch (msg.what) {
24767                case MSG_ON_PERMISSIONS_CHANGED: {
24768                    final int uid = msg.arg1;
24769                    handleOnPermissionsChanged(uid);
24770                } break;
24771            }
24772        }
24773
24774        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24775            mPermissionListeners.register(listener);
24776
24777        }
24778
24779        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24780            mPermissionListeners.unregister(listener);
24781        }
24782
24783        public void onPermissionsChanged(int uid) {
24784            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24785                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24786            }
24787        }
24788
24789        private void handleOnPermissionsChanged(int uid) {
24790            final int count = mPermissionListeners.beginBroadcast();
24791            try {
24792                for (int i = 0; i < count; i++) {
24793                    IOnPermissionsChangeListener callback = mPermissionListeners
24794                            .getBroadcastItem(i);
24795                    try {
24796                        callback.onPermissionsChanged(uid);
24797                    } catch (RemoteException e) {
24798                        Log.e(TAG, "Permission listener is dead", e);
24799                    }
24800                }
24801            } finally {
24802                mPermissionListeners.finishBroadcast();
24803            }
24804        }
24805    }
24806
24807    private class PackageManagerNative extends IPackageManagerNative.Stub {
24808        @Override
24809        public String[] getNamesForUids(int[] uids) throws RemoteException {
24810            final String[] results = PackageManagerService.this.getNamesForUids(uids);
24811            // massage results so they can be parsed by the native binder
24812            for (int i = results.length - 1; i >= 0; --i) {
24813                if (results[i] == null) {
24814                    results[i] = "";
24815                }
24816            }
24817            return results;
24818        }
24819    }
24820
24821    private class PackageManagerInternalImpl extends PackageManagerInternal {
24822        @Override
24823        public void setLocationPackagesProvider(PackagesProvider provider) {
24824            synchronized (mPackages) {
24825                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24826            }
24827        }
24828
24829        @Override
24830        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24831            synchronized (mPackages) {
24832                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24833            }
24834        }
24835
24836        @Override
24837        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24838            synchronized (mPackages) {
24839                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24840            }
24841        }
24842
24843        @Override
24844        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24845            synchronized (mPackages) {
24846                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24847            }
24848        }
24849
24850        @Override
24851        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24852            synchronized (mPackages) {
24853                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24854            }
24855        }
24856
24857        @Override
24858        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24859            synchronized (mPackages) {
24860                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24861            }
24862        }
24863
24864        @Override
24865        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24866            synchronized (mPackages) {
24867                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24868                        packageName, userId);
24869            }
24870        }
24871
24872        @Override
24873        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24874            synchronized (mPackages) {
24875                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24876                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24877                        packageName, userId);
24878            }
24879        }
24880
24881        @Override
24882        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24883            synchronized (mPackages) {
24884                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24885                        packageName, userId);
24886            }
24887        }
24888
24889        @Override
24890        public void setKeepUninstalledPackages(final List<String> packageList) {
24891            Preconditions.checkNotNull(packageList);
24892            List<String> removedFromList = null;
24893            synchronized (mPackages) {
24894                if (mKeepUninstalledPackages != null) {
24895                    final int packagesCount = mKeepUninstalledPackages.size();
24896                    for (int i = 0; i < packagesCount; i++) {
24897                        String oldPackage = mKeepUninstalledPackages.get(i);
24898                        if (packageList != null && packageList.contains(oldPackage)) {
24899                            continue;
24900                        }
24901                        if (removedFromList == null) {
24902                            removedFromList = new ArrayList<>();
24903                        }
24904                        removedFromList.add(oldPackage);
24905                    }
24906                }
24907                mKeepUninstalledPackages = new ArrayList<>(packageList);
24908                if (removedFromList != null) {
24909                    final int removedCount = removedFromList.size();
24910                    for (int i = 0; i < removedCount; i++) {
24911                        deletePackageIfUnusedLPr(removedFromList.get(i));
24912                    }
24913                }
24914            }
24915        }
24916
24917        @Override
24918        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24919            synchronized (mPackages) {
24920                // If we do not support permission review, done.
24921                if (!mPermissionReviewRequired) {
24922                    return false;
24923                }
24924
24925                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24926                if (packageSetting == null) {
24927                    return false;
24928                }
24929
24930                // Permission review applies only to apps not supporting the new permission model.
24931                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24932                    return false;
24933                }
24934
24935                // Legacy apps have the permission and get user consent on launch.
24936                PermissionsState permissionsState = packageSetting.getPermissionsState();
24937                return permissionsState.isPermissionReviewRequired(userId);
24938            }
24939        }
24940
24941        @Override
24942        public PackageInfo getPackageInfo(
24943                String packageName, int flags, int filterCallingUid, int userId) {
24944            return PackageManagerService.this
24945                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
24946                            flags, filterCallingUid, userId);
24947        }
24948
24949        @Override
24950        public ApplicationInfo getApplicationInfo(
24951                String packageName, int flags, int filterCallingUid, int userId) {
24952            return PackageManagerService.this
24953                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24954        }
24955
24956        @Override
24957        public ActivityInfo getActivityInfo(
24958                ComponentName component, int flags, int filterCallingUid, int userId) {
24959            return PackageManagerService.this
24960                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24961        }
24962
24963        @Override
24964        public List<ResolveInfo> queryIntentActivities(
24965                Intent intent, int flags, int filterCallingUid, int userId) {
24966            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24967            return PackageManagerService.this
24968                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24969                            userId, false /*resolveForStart*/);
24970        }
24971
24972        @Override
24973        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24974                int userId) {
24975            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24976        }
24977
24978        @Override
24979        public void setDeviceAndProfileOwnerPackages(
24980                int deviceOwnerUserId, String deviceOwnerPackage,
24981                SparseArray<String> profileOwnerPackages) {
24982            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24983                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24984        }
24985
24986        @Override
24987        public boolean isPackageDataProtected(int userId, String packageName) {
24988            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24989        }
24990
24991        @Override
24992        public boolean isPackageEphemeral(int userId, String packageName) {
24993            synchronized (mPackages) {
24994                final PackageSetting ps = mSettings.mPackages.get(packageName);
24995                return ps != null ? ps.getInstantApp(userId) : false;
24996            }
24997        }
24998
24999        @Override
25000        public boolean wasPackageEverLaunched(String packageName, int userId) {
25001            synchronized (mPackages) {
25002                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
25003            }
25004        }
25005
25006        @Override
25007        public void grantRuntimePermission(String packageName, String name, int userId,
25008                boolean overridePolicy) {
25009            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
25010                    overridePolicy);
25011        }
25012
25013        @Override
25014        public void revokeRuntimePermission(String packageName, String name, int userId,
25015                boolean overridePolicy) {
25016            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
25017                    overridePolicy);
25018        }
25019
25020        @Override
25021        public String getNameForUid(int uid) {
25022            return PackageManagerService.this.getNameForUid(uid);
25023        }
25024
25025        @Override
25026        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
25027                Intent origIntent, String resolvedType, String callingPackage,
25028                Bundle verificationBundle, int userId) {
25029            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
25030                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
25031                    userId);
25032        }
25033
25034        @Override
25035        public void grantEphemeralAccess(int userId, Intent intent,
25036                int targetAppId, int ephemeralAppId) {
25037            synchronized (mPackages) {
25038                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
25039                        targetAppId, ephemeralAppId);
25040            }
25041        }
25042
25043        @Override
25044        public boolean isInstantAppInstallerComponent(ComponentName component) {
25045            synchronized (mPackages) {
25046                return mInstantAppInstallerActivity != null
25047                        && mInstantAppInstallerActivity.getComponentName().equals(component);
25048            }
25049        }
25050
25051        @Override
25052        public void pruneInstantApps() {
25053            mInstantAppRegistry.pruneInstantApps();
25054        }
25055
25056        @Override
25057        public String getSetupWizardPackageName() {
25058            return mSetupWizardPackage;
25059        }
25060
25061        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
25062            if (policy != null) {
25063                mExternalSourcesPolicy = policy;
25064            }
25065        }
25066
25067        @Override
25068        public boolean isPackagePersistent(String packageName) {
25069            synchronized (mPackages) {
25070                PackageParser.Package pkg = mPackages.get(packageName);
25071                return pkg != null
25072                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
25073                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
25074                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
25075                        : false;
25076            }
25077        }
25078
25079        @Override
25080        public List<PackageInfo> getOverlayPackages(int userId) {
25081            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
25082            synchronized (mPackages) {
25083                for (PackageParser.Package p : mPackages.values()) {
25084                    if (p.mOverlayTarget != null) {
25085                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
25086                        if (pkg != null) {
25087                            overlayPackages.add(pkg);
25088                        }
25089                    }
25090                }
25091            }
25092            return overlayPackages;
25093        }
25094
25095        @Override
25096        public List<String> getTargetPackageNames(int userId) {
25097            List<String> targetPackages = new ArrayList<>();
25098            synchronized (mPackages) {
25099                for (PackageParser.Package p : mPackages.values()) {
25100                    if (p.mOverlayTarget == null) {
25101                        targetPackages.add(p.packageName);
25102                    }
25103                }
25104            }
25105            return targetPackages;
25106        }
25107
25108        @Override
25109        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
25110                @Nullable List<String> overlayPackageNames) {
25111            synchronized (mPackages) {
25112                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
25113                    Slog.e(TAG, "failed to find package " + targetPackageName);
25114                    return false;
25115                }
25116                ArrayList<String> overlayPaths = null;
25117                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
25118                    final int N = overlayPackageNames.size();
25119                    overlayPaths = new ArrayList<>(N);
25120                    for (int i = 0; i < N; i++) {
25121                        final String packageName = overlayPackageNames.get(i);
25122                        final PackageParser.Package pkg = mPackages.get(packageName);
25123                        if (pkg == null) {
25124                            Slog.e(TAG, "failed to find package " + packageName);
25125                            return false;
25126                        }
25127                        overlayPaths.add(pkg.baseCodePath);
25128                    }
25129                }
25130
25131                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
25132                ps.setOverlayPaths(overlayPaths, userId);
25133                return true;
25134            }
25135        }
25136
25137        @Override
25138        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
25139                int flags, int userId) {
25140            return resolveIntentInternal(
25141                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
25142        }
25143
25144        @Override
25145        public ResolveInfo resolveService(Intent intent, String resolvedType,
25146                int flags, int userId, int callingUid) {
25147            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
25148        }
25149
25150        @Override
25151        public void addIsolatedUid(int isolatedUid, int ownerUid) {
25152            synchronized (mPackages) {
25153                mIsolatedOwners.put(isolatedUid, ownerUid);
25154            }
25155        }
25156
25157        @Override
25158        public void removeIsolatedUid(int isolatedUid) {
25159            synchronized (mPackages) {
25160                mIsolatedOwners.delete(isolatedUid);
25161            }
25162        }
25163
25164        @Override
25165        public int getUidTargetSdkVersion(int uid) {
25166            synchronized (mPackages) {
25167                return getUidTargetSdkVersionLockedLPr(uid);
25168            }
25169        }
25170
25171        @Override
25172        public boolean canAccessInstantApps(int callingUid, int userId) {
25173            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
25174        }
25175    }
25176
25177    @Override
25178    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
25179        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
25180        synchronized (mPackages) {
25181            final long identity = Binder.clearCallingIdentity();
25182            try {
25183                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
25184                        packageNames, userId);
25185            } finally {
25186                Binder.restoreCallingIdentity(identity);
25187            }
25188        }
25189    }
25190
25191    @Override
25192    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
25193        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
25194        synchronized (mPackages) {
25195            final long identity = Binder.clearCallingIdentity();
25196            try {
25197                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
25198                        packageNames, userId);
25199            } finally {
25200                Binder.restoreCallingIdentity(identity);
25201            }
25202        }
25203    }
25204
25205    private static void enforceSystemOrPhoneCaller(String tag) {
25206        int callingUid = Binder.getCallingUid();
25207        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
25208            throw new SecurityException(
25209                    "Cannot call " + tag + " from UID " + callingUid);
25210        }
25211    }
25212
25213    boolean isHistoricalPackageUsageAvailable() {
25214        return mPackageUsage.isHistoricalPackageUsageAvailable();
25215    }
25216
25217    /**
25218     * Return a <b>copy</b> of the collection of packages known to the package manager.
25219     * @return A copy of the values of mPackages.
25220     */
25221    Collection<PackageParser.Package> getPackages() {
25222        synchronized (mPackages) {
25223            return new ArrayList<>(mPackages.values());
25224        }
25225    }
25226
25227    /**
25228     * Logs process start information (including base APK hash) to the security log.
25229     * @hide
25230     */
25231    @Override
25232    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
25233            String apkFile, int pid) {
25234        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25235            return;
25236        }
25237        if (!SecurityLog.isLoggingEnabled()) {
25238            return;
25239        }
25240        Bundle data = new Bundle();
25241        data.putLong("startTimestamp", System.currentTimeMillis());
25242        data.putString("processName", processName);
25243        data.putInt("uid", uid);
25244        data.putString("seinfo", seinfo);
25245        data.putString("apkFile", apkFile);
25246        data.putInt("pid", pid);
25247        Message msg = mProcessLoggingHandler.obtainMessage(
25248                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
25249        msg.setData(data);
25250        mProcessLoggingHandler.sendMessage(msg);
25251    }
25252
25253    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
25254        return mCompilerStats.getPackageStats(pkgName);
25255    }
25256
25257    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
25258        return getOrCreateCompilerPackageStats(pkg.packageName);
25259    }
25260
25261    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
25262        return mCompilerStats.getOrCreatePackageStats(pkgName);
25263    }
25264
25265    public void deleteCompilerPackageStats(String pkgName) {
25266        mCompilerStats.deletePackageStats(pkgName);
25267    }
25268
25269    @Override
25270    public int getInstallReason(String packageName, int userId) {
25271        final int callingUid = Binder.getCallingUid();
25272        enforceCrossUserPermission(callingUid, userId,
25273                true /* requireFullPermission */, false /* checkShell */,
25274                "get install reason");
25275        synchronized (mPackages) {
25276            final PackageSetting ps = mSettings.mPackages.get(packageName);
25277            if (filterAppAccessLPr(ps, callingUid, userId)) {
25278                return PackageManager.INSTALL_REASON_UNKNOWN;
25279            }
25280            if (ps != null) {
25281                return ps.getInstallReason(userId);
25282            }
25283        }
25284        return PackageManager.INSTALL_REASON_UNKNOWN;
25285    }
25286
25287    @Override
25288    public boolean canRequestPackageInstalls(String packageName, int userId) {
25289        return canRequestPackageInstallsInternal(packageName, 0, userId,
25290                true /* throwIfPermNotDeclared*/);
25291    }
25292
25293    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
25294            boolean throwIfPermNotDeclared) {
25295        int callingUid = Binder.getCallingUid();
25296        int uid = getPackageUid(packageName, 0, userId);
25297        if (callingUid != uid && callingUid != Process.ROOT_UID
25298                && callingUid != Process.SYSTEM_UID) {
25299            throw new SecurityException(
25300                    "Caller uid " + callingUid + " does not own package " + packageName);
25301        }
25302        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
25303        if (info == null) {
25304            return false;
25305        }
25306        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
25307            return false;
25308        }
25309        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
25310        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
25311        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
25312            if (throwIfPermNotDeclared) {
25313                throw new SecurityException("Need to declare " + appOpPermission
25314                        + " to call this api");
25315            } else {
25316                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
25317                return false;
25318            }
25319        }
25320        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
25321            return false;
25322        }
25323        if (mExternalSourcesPolicy != null) {
25324            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
25325            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
25326                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
25327            }
25328        }
25329        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
25330    }
25331
25332    @Override
25333    public ComponentName getInstantAppResolverSettingsComponent() {
25334        return mInstantAppResolverSettingsComponent;
25335    }
25336
25337    @Override
25338    public ComponentName getInstantAppInstallerComponent() {
25339        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25340            return null;
25341        }
25342        return mInstantAppInstallerActivity == null
25343                ? null : mInstantAppInstallerActivity.getComponentName();
25344    }
25345
25346    @Override
25347    public String getInstantAppAndroidId(String packageName, int userId) {
25348        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25349                "getInstantAppAndroidId");
25350        enforceCrossUserPermission(Binder.getCallingUid(), userId,
25351                true /* requireFullPermission */, false /* checkShell */,
25352                "getInstantAppAndroidId");
25353        // Make sure the target is an Instant App.
25354        if (!isInstantApp(packageName, userId)) {
25355            return null;
25356        }
25357        synchronized (mPackages) {
25358            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25359        }
25360    }
25361
25362    boolean canHaveOatDir(String packageName) {
25363        synchronized (mPackages) {
25364            PackageParser.Package p = mPackages.get(packageName);
25365            if (p == null) {
25366                return false;
25367            }
25368            return p.canHaveOatDir();
25369        }
25370    }
25371
25372    private String getOatDir(PackageParser.Package pkg) {
25373        if (!pkg.canHaveOatDir()) {
25374            return null;
25375        }
25376        File codePath = new File(pkg.codePath);
25377        if (codePath.isDirectory()) {
25378            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25379        }
25380        return null;
25381    }
25382
25383    void deleteOatArtifactsOfPackage(String packageName) {
25384        final String[] instructionSets;
25385        final List<String> codePaths;
25386        final String oatDir;
25387        final PackageParser.Package pkg;
25388        synchronized (mPackages) {
25389            pkg = mPackages.get(packageName);
25390        }
25391        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25392        codePaths = pkg.getAllCodePaths();
25393        oatDir = getOatDir(pkg);
25394
25395        for (String codePath : codePaths) {
25396            for (String isa : instructionSets) {
25397                try {
25398                    mInstaller.deleteOdex(codePath, isa, oatDir);
25399                } catch (InstallerException e) {
25400                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25401                }
25402            }
25403        }
25404    }
25405
25406    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25407        Set<String> unusedPackages = new HashSet<>();
25408        long currentTimeInMillis = System.currentTimeMillis();
25409        synchronized (mPackages) {
25410            for (PackageParser.Package pkg : mPackages.values()) {
25411                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25412                if (ps == null) {
25413                    continue;
25414                }
25415                PackageDexUsage.PackageUseInfo packageUseInfo =
25416                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
25417                if (PackageManagerServiceUtils
25418                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25419                                downgradeTimeThresholdMillis, packageUseInfo,
25420                                pkg.getLatestPackageUseTimeInMills(),
25421                                pkg.getLatestForegroundPackageUseTimeInMills())) {
25422                    unusedPackages.add(pkg.packageName);
25423                }
25424            }
25425        }
25426        return unusedPackages;
25427    }
25428}
25429
25430interface PackageSender {
25431    void sendPackageBroadcast(final String action, final String pkg,
25432        final Bundle extras, final int flags, final String targetPkg,
25433        final IIntentReceiver finishedReceiver, final int[] userIds);
25434    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
25435        boolean includeStopped, int appId, int... userIds);
25436}
25437